python - 在程序中创建 Tkinter 框时出现问题
问题描述
frame = Frame(root, width=300, height=250)
没有正确创建 Tkinter 窗口。你能找到问题并告诉我它是什么。如果它有帮助,我确实拥有其余的代码。
def clicking_pad(worker_1):
root = Tk()
global left_click
def left_click(store: object) -> object:
return store
global right_click
def right_click(store: object) -> object:
return store
frame = Frame(root, width=300, height=250)
frame.bind("<Button-1>", left_click("GO"))
frame.bind("<Button-2>", right_click("STOP"))
frame.pack()
root.mainloop()
return right_click == right_click(store)
解决方案
正如 Bryan Oakley 所说,您的代码可以Frame
毫无问题地创建。
我也不知道您的意思是“未正确创建 Tkinter 窗口”。
正如 acw1668 所说,您在代码中有一些错误:
- 您不能对变量和函数使用相同的名称 -
left_click
,right_click
bind()
(类似于command=
andafter()
)需要函数名称 - 这意味着没有()
。它被称为“回调”。如果您需要使用带参数的函数,那么您可以创建不带参数的函数来运行带参数的函数。您也可以使用lambda
直接在bind()
bind()
无法从函数中获取结果,因此return
您必须将结果分配给global
变量,然后您可以在函数之外获取它,而不是使用。
我的观点:
<Button-2>
是中键,<Button-3>
是右键。bind()
期望得到一个参数的回调 -event
.
import tkinter as tk
def clicking_pad(worker_1):
global left_click
global right_click
def on_left_click(store: object) -> object:
#return store
global left_click
left_click = store
print('[INSIDE] left_click:', left_click)
def on_right_click(store: object) -> object:
#return store
global right_click
right_click = store
print('[INSIDE] right_click:', right_click)
root = tk.Tk()
frame = tk.Frame(root, width=300, height=250)
frame.pack()
frame.bind("<Button-1>", lambda event:on_left_click("GO"))
frame.bind("<Button-3>", lambda event:on_right_click("STOP"))
root.mainloop()
print('[OUTSIDE] left_click:', left_click)
print('[OUTSIDE] right_click:', right_click)
clicking_pad(None)
编辑:没有lambda
def on_button_1(event):
on_left_click("GO")
def on_button_3(event):
on_right_click("STOP")
frame.bind("<Button-1>", on_button_1)
frame.bind("<Button-3>", on_button_3)
或者如果你的函数返回值
def on_button_1(event):
global result
result = on_left_click("GO")
def on_button_3(event):
global result
result = on_right_click("STOP")
frame.bind("<Button-1>", on_button_1)
frame.bind("<Button-3>", on_button_3)
推荐阅读
- c# - 如何将“多行文本框”插入 SQL Server 中的 1 列?
- python - 提高非常大文件读取行的 for 循环速度
- c# - foreach 在遍历所有列表之前结束
- c# - 获取自定义 ContentType 以在 VSIX 扩展中注册自动完成
- python - Python-for循环中的最后一项不能添加到字典中
- php - PHP 错误修复 - 条件无法正常工作
- c# - 从任意线程调用 StateHasChanged() 是否安全?
- animation - 补间动画和动画控制器的区别
- sql - SQL 数组中缺少结果
- angular - 如何从菜单组件中导出数据,以便在相应的html组件中使用