【问题标题】:tkinter python program structuretkinter python 程序结构
【发布时间】:2020-02-02 17:23:45
【问题描述】:

我是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 有很多可能性:脚本、模块、面向对象……)

我该如何解决这个问题?

【问题讨论】:

标签: python tkinter


【解决方案1】:

您将需要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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 2017-05-30
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2013-07-22
    相关资源
    最近更新 更多