Вот код, который у меня есть (с лучшим стилем):
Код: Выделить всё
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.
Обратите внимание: определение make_confirmation находится в классе 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
Другими словами, это работает:
Код: Выделить всё
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()
Но команда = self.make_confirmation работает?
Почему команда = root.quit работает? п>
Подробнее здесь: https://stackoverflow.com/questions/785 ... root-close