Вызов вложенной функции сводит на нет все обоснования элементов в окне - PullRequest
0 голосов
/ 01 августа 2020

Я пытаюсь создать функциональную кнопку очистки, которая удаляет весь мой ввод из полей ввода в окне «Arithmeti c Sequence», но всякий раз, когда я пытаюсь вызвать вложенную функцию в Button, чтобы сделать ее функциональной, все выравнивания, которые я сделал с помощью .grid () во втором окне, разрушены.

from tkinter import *

class mainTitle(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        myTitle = Label(self, text="Arithmetic & Geometric Sequence Calculator", font=("bold", 15))
        myTitle.grid(row=1, column=1, pady=50)
        
        opLabel = Label(self, text="Chooose either Arithmetic & Geometric series to calculate")
        opLabel.grid(row=2, column=1, pady=10)
        
        self.quitButton = Button(self, text="Quit", command=self.qProgram)
        self.quitButton.place(relx=0.9, rely=0.9)
        
        self.ariButton = Button(self, text="Arithmetic Sequence", command=self.ariClick)
        self.ariButton.grid(row=3, column=1)
        self.geoButton = Button(self, text="Geometric Sequence", command=self.geoClick)
        self.geoButton.grid(row=4, column=1, pady=10)

        self.grid_rowconfigure(0, weight=1)
        self.grid_rowconfigure(5, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(2, weight=1)

    def ariClick(Frame):
        ariWindow = Toplevel()
        ariWindow.geometry("375x375")
        ariWindow.title("Arithmetic Sequence")
        
        ariWindow.inputTitle = Label(ariWindow, text="Enter input for each value below", anchor="e")
        ariWindow.inputTitle.place(relx=0.29, rely=0.25)
        
        aLbl = Label(ariWindow, text="a:")
        aLbl.grid(row=1, column=1)
        aEntry = Entry(ariWindow)
        aEntry.grid(row=1, column=2)
        
        dLbl = Label(ariWindow, text="d:")
        dLbl.grid(row=2, column=1)
        dEntry = Entry(ariWindow)
        dEntry.grid(row=2, column=2)
        
        nLbl = Label(ariWindow, text="n:")
        nLbl.grid(row=3, column=1)
        nEntry = Entry(ariWindow)
        nEntry.grid(row=3, column=2)
        
        clrButton = Button(ariWindow, text="Clear", command=ariWindow.clear)
        #Issue is here - whenever I try to call clear(), all the justifications I did with grid and weight messes up
        #But, if you remove command=Window.clear, everything is back to normal but the clear button has no function
        clrButton.grid(row=4, column=2, pady=10)
        
        ariWindow.grid_rowconfigure(0, weight=1)
        ariWindow.grid_rowconfigure(5, weight=1)
        ariWindow.grid_columnconfigure(0, weight=1)
        ariWindow.grid_columnconfigure(3, weight=1)
            
        ariWindow.closeButton = Button(ariWindow, text="Close", command=ariWindow.destroy)
        ariWindow.closeButton.place(relx=0.85, rely=0.9)
                   
        def clear():
            print("This is working")
            
    def geoClick(Frame):
        geoWindow = Toplevel()
        geoWindow.geometry("500x500")
        geoWindow.title("Geometric Sequence")
        
    def qProgram(Frame):
        root.destroy()

if __name__ == "__main__":
    root = Tk()
    root.geometry("500x500")
    mainTitle(root).grid(sticky="nsew")
    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)
    root.mainloop()

Что я делаю не так? Извините, я новичок в Tkinter и программировании в целом

Ответы [ 2 ]

2 голосов
/ 01 августа 2020

Когда я выполняю ваш код и нажимаю кнопку Arithmetic Sequence, я получаю следующую ошибку:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python38\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "D:\Temp\python\demo1.py", line 48, in ariClick
    clrButton = Button(ariWindow, text="Clear", command=ariWindow.clear)
AttributeError: 'Toplevel' object has no attribute 'clear'

Таким образом, код из строки ошибки и далее внутри функции ariClick() не будет выполняться, и это вызывает беспорядок.

Измените command=ariWindow.clear на command=clear и переместите определение clear() в начало функции ariCick():

def ariClick(Frame):
    def clear():
        print("This is working")
        
    ariWindow = Toplevel()
    ariWindow.geometry("375x375")
    ariWindow.title("Arithmetic Sequence")
    
    ariWindow.inputTitle = Label(ariWindow, text="Enter input for each value below", anchor="e")
    ariWindow.inputTitle.place(relx=0.29, rely=0.25)
    
    aLbl = Label(ariWindow, text="a:")
    aLbl.grid(row=1, column=1)
    aEntry = Entry(ariWindow)
    aEntry.grid(row=1, column=2)
    
    dLbl = Label(ariWindow, text="d:")
    dLbl.grid(row=2, column=1)
    dEntry = Entry(ariWindow)
    dEntry.grid(row=2, column=2)
    
    nLbl = Label(ariWindow, text="n:")
    nLbl.grid(row=3, column=1)
    nEntry = Entry(ariWindow)
    nEntry.grid(row=3, column=2)
    
    clrButton = Button(ariWindow, text="Clear", command=clear)
    clrButton.grid(row=4, column=2, pady=10)
    
    ariWindow.grid_rowconfigure(0, weight=1)
    ariWindow.grid_rowconfigure(5, weight=1)
    ariWindow.grid_columnconfigure(0, weight=1)
    ariWindow.grid_columnconfigure(3, weight=1)
        
    ariWindow.closeButton = Button(ariWindow, text="Close", command=ariWindow.destroy)
    ariWindow.closeButton.place(relx=0.85, rely=0.9)
0 голосов
/ 01 августа 2020

Вызвать такую ​​функцию, как qProgram, в свойстве команды в определении clrButton и очистить записи с помощью Entry.delete(0, END) или Entry.delete(0, 'end') в новой функции.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...