我希望创建一个带有几个按钮的窗口,通过单击每个按钮,可以选择特定的数据库并执行某些代码,这些代码由变量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>
有什么问题吗? 提前感谢你们的帮助:)
这个错误是不言自明的。可以看到这些垃圾,因为您正在打印函数,而不是使用参数调用函数
我建议在每次单击按钮调用
selDB
函数时,将print
语句移到selDB
函数中编辑
由于需要访问程序其余部分的DB名称,因此还需要添加全局变量或使用类变量(如果使用的是类),如下所示:
现在,数据库名称将存储在
DB
中,并且可以在整个程序中访问另一个提示是,不要使用以下方法:
button_1 = Button(root, text='database 1', command=lambda :selDB(1)) .pack()
在这种情况下
button1
保持None
。相反,请执行以下操作:现在
button1
保存对创建的Button
小部件的引用相关问题 更多 >
编程相关推荐