使用tkinter中的按钮,将某个变量传递给代码的其余部分并关闭wind

2024-10-02 18:21:06 发布

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

我希望创建一个带有几个按钮的窗口,通过单击每个按钮,可以选择特定的数据库并执行某些代码,这些代码由变量DB(最后一行)的“print”函数表示。这就是为什么要回答第一个建议的答案,我不能移动此print命令的位置

守则:

from tkinter import *
def selDB (x):
    DB = None
    if x==1:
        DB = 'database001'
    else:
        DB= 'database002'
    root.destroy()
    print(DB)
    return DB

root= Tk()
button_1 = Button(root, text='database 1', command=lambda :selDB(1)) .pack()
button_2=  Button(root, text='database 2', command=lambda :selDB(2)) .pack()
root.mainloop() 

print('database is:',selDB)

如果我按下“Button1”,我希望x=1,并且selDB函数会为其余代码返回DB='database001'。我希望在last print函数的输出中看到这一点: database is: database001 但我得到的却是这些废话: database is: <function selDB at 0x000002A736308DC8>

有什么问题吗? 提前感谢你们的帮助:)


Tags: lambda函数代码textdbisbuttonroot
1条回答
网友
1楼 · 发布于 2024-10-02 18:21:06

这个错误是不言自明的。可以看到这些垃圾,因为您正在打印函数,而不是使用参数调用函数

我建议在每次单击按钮调用selDB函数时,将print语句移到selDB函数中

def selDB (x):
    DB = None
    if x==1:
        print('database is: database 1')
        DB = 'database001'
    else:
        print('database is: database 2')
        DB= 'database002'
    root.destroy()
    return DB #makes no sense as this return value is not being used or stored anywhere

编辑

由于需要访问程序其余部分的DB名称,因此还需要添加全局变量或使用类变量(如果使用的是类),如下所示:

DB = None # define the global variable DB
def selDB (x):
    global DB
    if x==1:
        print('database is: database 1')
        DB = 'database001'
    else:
        print('database is: database 2')
        DB= 'database002'
    root.destroy() # why do you want to destroy root? delete if not needed
    return

现在,数据库名称将存储在DB中,并且可以在整个程序中访问

另一个提示是,不要使用以下方法:

button_1 = Button(root, text='database 1', command=lambda :selDB(1)) .pack()

在这种情况下button1保持None。相反,请执行以下操作:

button_1 = Button(root, text='database 1', command=lambda :selDB(1))
button1.pack()

现在button1保存对创建的Button小部件的引用

相关问题 更多 >