我试着用下面的代码来创建两个按钮,当你按下一个按钮时,会显示出一个按钮,当另一个按钮被按下,会隐藏这个按钮,但是很明显,这是不起作用的--我认为这主要是因为我无法理解布尔人在python中是如何工作的,所以如果有人能帮我,我会非常感激的。
from tkinter import *
#first window
master= Tk()
master.geometry('1440x900+0+0')
master.title('DMX512 Controller')
#buttons
bw=250
bh=110
bool1show = False
Button(master,text="show the slider", command =bool1show= True).place(x=800,y=10)
Button(master,text="hide the slider", command = bool1show= not True).place(x=900,y=10)
#slider characteristics
slw=130
sll=600
sly=1
stc='blue'
if bool1show==True:
Scale(master, from_=255, to=0, length =sll,width =slw, troughcolor = stc).grid(row=sly,column=5)
if bool1show==not True:
Scale(from_=255, to=0, length =sll,width =slw, troughcolor = stc).grid(row=sly,column=5)
发布于 2013-12-19 20:38:35
您必须在command
参数中提供对函数的引用,而bool1show= True
不是对函数的引用。但是,由于您所做的只是显示或隐藏一个小部件,所以您根本不需要使用布尔变量,除非您使用的是无线电按钮(而不是)。
对于您发布的代码,您只需要两个函数:一个显示滑块,另一个隐藏它。为此,只需创建一次缩放,然后使用grid
方法来显示和隐藏它。要做到这一点,您必须通过在全局变量中保存一个引用来“记住”scale小部件。
def show_scale():
# note: grid will remember the values you used when you first called grid
the_scale.grid()
def hide_scale():
# this removes the scale from view, but remembers where it was
the_scale.grid_remove()
the_scale = Scale(master, from_=255, to=0, length =sll,width =slw, troughcolor = stc)
the_scale.grid(row=sly, column=5)
...
Button(master,text="show the slider", command show_scale).place(x=800,y=10)
Button(master,text="hide the slider", command hide_scale).place(x=900,y=10)
关于一个无关的问题,我强烈建议你不要使用场所。您的GUI将更易于编写和维护,并且在不同分辨率或不同字体的系统上进行调整或运行时,它们的行为会更好。
发布于 2013-12-19 19:33:44
您的代码中有一些不明确之处,所以我不确定您想要实现什么。如果要验证True条件,可以执行以下操作:
if bool1show == True:
do stuff...
#or
if bool1show:
do stuff...
如果bool1show==not True:不工作。如果你真的想这样做,你可以这样做:
if bool1show==(not True)
#or better:
if bool1show == False
#even better:
if not bool1show:
希望这有助于更好地理解蟒布尔人。
发布于 2013-12-19 19:40:22
如果将command
参数分配给调用另一个函数的lambda函数如何:
Button(master,text="show the slider", command=lambda: bool_func(bool1show).place(x=800,y=10)
Button(master,text="hide the slider",command=lambda: bool_func(bool1show,b=False).place(x=900,y=10)
其中:
def bool_func(variable, b=True): # b is True by default, hence you don't provide the argument in the first Button statement.
variable = b
return variable
有关lambda函数的一些信息,请参阅这里
https://stackoverflow.com/questions/20689972
复制相似问题