tkinter python程序结构

2024-05-15 05:49:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python编程新手,程序结构有点问题: 当我在python的主要部分中创建GUI时,代码可以正常工作:

import tkinter as tk

root = tk.Tk()
root.overrideredirect(True)
root.geometry("800x480")

def cb_Gebruiker():
    btnUser["text"]= "changed"

btnUser = tk.Button(root, text="User",command = cb_Gebruiker)
btnUser.place(x=1,y=1,width="300",height="73")


root.mainloop()

当我在函数中创建GUI时,btn变量是本地变量,因此这不起作用

def MakeBtn():
    btnUser = tk.Button(root, text="User",command = cb_Gebruiker)
    btnUser.place(x=1,y=1,width="300",height="73")

def cb_Gebruiker():
    btnUser["text"]= "changed"

MakeBtn()


root.mainloop()

现在我有一个相当大的程序,我希望我的GUI在一个单独的文件中,但是我不能访问我的GUI组件。。。 我似乎找不到关于如何构造程序的教程(python有很多可能性:脚本、模块、面向对象等等)

我如何解决这个问题


Tags: textdefplaceguibuttonrootwidthcommand
1条回答
网友
1楼 · 发布于 2024-05-15 05:49:50

您将需要一个lambda来延迟对带有参数的命令的调用


def MakeBtn():
    btnUser = tk.Button(root, text="User", command = lambda: cb_Gebruiker(btnUser))
    btnUser.place(x=1, y=1, width="300", height="73")

def cb_Gebruiker(btnUser):
    btnUser["text"] = "changed"

MakeBtn()


root.mainloop()

相关问题 更多 >

    热门问题