我正在嘗試學習 tkinter。我從這里的一個例子開始;https://www.pythontutorial.net/tkinter/tkinter-object-oriented-frame/。我的所有按鈕都在 MainFrame(ttk.Frame) 類中,我想使用其中一個按鈕退出應用程式,但我不知道該怎么做。有人可以幫忙嗎?
import tkinter as tk
from tkinter import ttk
class MainFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
app = App()
self.style2 = {'fg': 'black', 'bg': '#e95420', 'activebackground': 'coral', 'activeforeground': '#2f2f2f'}
self.exit=tk.Button(self , compound=tk.RIGHT, text='exit', width=20, relief="solid")
self.exit['command'] = self.exit_test
self.exit.pack(expand=False, padx=0, pady=100, ipadx=10, ipady=10, side=tk.BOTTOM)
self.exit.configure(self.style2)
self.pack()
def exit_test(self):
app.exit()
class StatusBar(tk.Frame):
def __init__(self, container):
super().__init__(container)
self.variable=tk.StringVar()
self.variable.set("add the current time here")
self.label=tk.Label(self, bd=0, relief="solid", height="2", width="1500", textvariable=self.variable, foreground="white", background='#2f2f2f', font=('helvetica',9))
self.label.pack()
self.pack(fill="x", side="bottom", ipady=0, padx=0, pady=0)
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("1500x1100")
def exit_app():
self.container.exit()
if __name__ == "__main__":
app = App()
frame = StatusBar(app)
frame = MainFrame(app)
app.mainloop()
uj5u.com熱心網友回復:
以下是如何實作我在評論中的建議(container.exit從 a呼叫Button)。
import tkinter as tk
from tkinter import ttk
class MainFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
self.style2 = {'fg': 'black', 'bg': '#e95420', 'activebackground': 'coral',
'activeforeground': '#2f2f2f'}
self.exit = tk.Button(self, compound=tk.RIGHT, text='Exit', width=20,
relief="solid", command=container.exit)
self.exit.pack(expand=False, padx=0, pady=100, ipadx=10, ipady=10, side=tk.BOTTOM)
self.exit.configure(self.style2)
self.pack()
class StatusBar(tk.Frame):
def __init__(self, container):
super().__init__(container)
self.variable = tk.StringVar()
self.variable.set("add the current time here")
self.label=tk.Label(self, bd=0, relief="solid", height="2", width="1500",
textvariable=self.variable, foreground="white",
background='#2f2f2f', font=('helvetica',9))
self.label.pack()
self.pack(fill="x", side="bottom", ipady=0, padx=0, pady=0)
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("1500x1100")
def exit(self):
self.destroy()
if __name__ == "__main__":
app = App()
sb = StatusBar(app)
mf = MainFrame(app)
app.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/357576.html
