Python tkinter回调
我有一个带有一组框架的容器,它为我提供了两个页面(主页和信息页面)。按钮用于导航页面。 一切正常 我已经定义了一个函数来删除操作系统上的文件夹。(shutil.rmtree)这个函数应该由主页上的我的按钮2调用,但是它掉了下来,不起作用Python tkinter回调,python,tkinter,Python,Tkinter,我有一个带有一组框架的容器,它为我提供了两个页面(主页和信息页面)。按钮用于导航页面。 一切正常 我已经定义了一个函数来删除操作系统上的文件夹。(shutil.rmtree)这个函数应该由主页上的我的按钮2调用,但是它掉了下来,不起作用 import tkinter as tk import shutil from tkinter import * TITLE_FONT = ("Helvetica", 18, "bold") class App(tk.Tk): de
import tkinter as tk
import shutil
from tkinter import *
TITLE_FONT = ("Helvetica", 18, "bold")
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (MainPage, InfoPage,):
frame = F(container, self)
self.frames[F] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(MainPage)
def show_frame(self, c):
'''Show a frame for the given class'''
frame = self.frames[c]
frame.tkraise()
class MainPage(tk.Frame):
def callback(self):
shutil.rmtree('C:\Test', ignore_errors=False)
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
photo = PhotoImage(file='C:\Logo.gif')
label = Label(self, image=photo)
label.Image = photo
label.pack(side=TOP)
button1 = tk.Button(self, text="Info!",
command=lambda: controller.show_frame(InfoPage))
button1.pack(side=LEFT, padx=5, pady=5)
button2 = tk.Button(self, text="Clean!", command=callback)
button2.pack(side=RIGHT, padx=5, pady=5)
class InfoPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Info Page", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Back",
command=lambda: controller.show_frame(MainPage))
button.pack()
if __name__ == "__main__":
app = App()
app.mainloop()
您应该像设置f.e.按钮1一样设置按钮2的动作。回调是没有参数的函数,但您提供的函数只有一个参数。。。同时尽量把你的代码精简到最低限度,当只有几行代码的时候,你会更容易发现你的问题所在。我仍然无法正确地理解它…这让我发疯!获取“callback is not defined”(回调未定义)请尝试以下操作:
tk.Button(self,text=“Clean!”,command=lambda:self.callback())
@linluk:如果不传递任何参数,则绝对没有理由使用lambda
。这两个完全相同:command=self.callback
,command=lambda:self.callback())
<代码>lambda增加了复杂性,但在这种情况下没有增加任何价值。