首页 > 解决方案 > 在程序中创建 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)

标签: pythontkinter

解决方案


正如 Bryan Oakley 所说,您的代码可以Frame毫无问题地创建。
我也不知道您的意思是“未正确创建 Tkinter 窗口”。

正如 acw1668 所说,您在代码中有一些错误:

  1. 您不能对变量和函数使用相同的名称 - left_clickright_click
  2. bind()(类似于command=and after())需要函数名称 - 这意味着没有()。它被称为“回调”。如果您需要使用带参数的函数,那么您可以创建不带参数的函数来运行带参数的函数。您也可以使用lambda直接在bind()
  3. bind()无法从函数中获取结果,因此return您必须将结果分配给global变量,然后您可以在函数之外获取它,而不是使用。

我的观点:

  1. <Button-2>是中键,<Button-3>是右键。
  2. 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)

推荐阅读