布尔值工作不正常

2024-05-16 00:31:32 发布

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

我试图让下面的代码来创建两个按钮,当你按下一个按钮时,将显示音量控制器,当按下另一个按钮时,将隐藏音量控制器,但显然这是不起作用,我认为这主要是因为我不能得到我的头如何布尔在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)

Tags: thetextfrommastertruebutton控制器按钮
3条回答

如果将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函数的一些信息,请查看here

必须在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)

另一方面,我强烈建议您不要使用place。您的gui将更易于编写和维护,并且在调整大小或在具有不同分辨率或不同字体的系统上运行时,它们的表现会更好。你知道吗

你的代码有点模棱两可,所以我不确定你想达到什么目的。如果要验证真实情况,可以执行以下操作:

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:

希望这有助于更好地理解python布尔函数

相关问题 更多 >