作为完整应用程序的过渡,我将关闭文件中不同位置的按钮窗口。现在,它最初工作得很好:我可以从文件中的两个位置关闭应用程序。然而,我正在努力清理代码,并拥有更好的样式。
以下是我的代码(具有更好的样式):
from tkinter import *
from tkinter import ttk
class Location:
def __init__(self, root):
root.title("Location")
root.geometry('400x295')
self.mainframe = ttk.Frame(root, padding="3 3 12 12")
self.mainframe.grid(column = 0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
confirm_button = ttk.Button(self.mainframe, text = 'CONFIRM', command = self.make_confirmation)
confirm_button.grid(column=0, row=0)
select_button = ttk.Button(self.mainframe, text = 'Geometry', command = root.quit)
select_button.grid(column=0, row=1)
def make_confirmation(self, *args):
root.quit()
def main_app():
root = Tk()
Location(root)
root.mainloop()
if __name__ == "__main__":
main_app()
“几何体”按钮将很好地关闭。
“确认”按钮给我一个
NameError
.
笔记
def make_confirmation
在中
class Location
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "c:\Users\User\Documents\Python\Tutorials\Quit_wStyle.py", line 22, in make_confirmation
root.quit()
^^^^
NameError: name 'root' is not defined
在我的非MWE中,
make.confirmation
做了更多的工作,并通过了论证。这一切都很好。我知道这一点,因为当我摆脱
def main_app():
把它都放进去
if __name__ == "__main__":
,然后两者
root.quit
作品
换言之,这是有效的:
from tkinter import *
from tkinter import ttk
class Location:
def __init__(self, root):
root.title("Location")
root.geometry('400x295')
self.mainframe = ttk.Frame(root, padding="3 3 12 12")
self.mainframe.grid(column = 0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
confirm_button = ttk.Button(self.mainframe, text = 'CONFIRM', command = self.make_confirmation)
confirm_button.grid(column=0, row=0)
select_button = ttk.Button(self.mainframe, text = 'Geometry', command = root.quit)
select_button.grid(column=0, row=1)
def make_confirmation(self, *args):
root.quit()
if __name__ == "__main__":
main_app()
root = Tk()
Location(root)
root.mainloop()
为什么
command = root.quit
工作
但是
command = self.make_confirmation
工作吗?