在Python中动态更改Button文本

时间:2015-09-19 13:04:32

标签: python button tkinter

有人可以向我解释为什么以下代码不起作用吗?

这仍然是一个程序的空壳,而且我现在都在努力做 是当我单击连接按钮时,它会更改文本以断开连接。 我也想改变命令,但我确定我是否能够改变 我应该能够改变命令的文本。

每当我点击按钮时,都会出现以下错误

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:/Users/Rudolf/Desktop/test.py", line 5, in Connect
    if btnConnect["text"] == "Connect":
TypeError: 'NoneType' object is not subscriptable

我不明白。它看起来如此简单和合乎逻辑。请帮忙。

有问题的代码:

from tkinter import *

def Connect():   
    """Clicking the connect button"""
    if btnConnect["text"] == "Connect":
        btnConnect["text"] = "Disconnect"
    else:
        btnConnect["text"] = "Connect"

#Part in question^^

mGui = Tk()

mGui.geometry('500x420+1000+200')
mGui.title('PythonGUI')

#Variables:
cmdText = StringVar()


####################


#Heading
lblHead = Label(mGui, text='Distance Meassurement Device', font=("Helvetica", 18, "underline")).place(x=75,y=10)

#Connect Button and Label
btnConnect = Button(mGui, text = "Connect", command = Connect).place(x=20,y=70)
lblConnect = Label(mGui, text = 'Currently disconnected').place(x=20,y=100)

#Baud rate & COM port Labels
lblBaud = Label(mGui, text = 'Baud Rate : x').place(x=350,y=70)
lblCom = Label(mGui, text = 'COM port : x').place(x=350,y=90)

#Calibrate Buttons
btnCal0 = Button(mGui, text = 'Calibrate 0').place(x=20,y=200)
btnCal1 = Button(mGui, text = 'Calibrate 1').place(x=20,y=240)

#Stream Button
btnStream = Button(mGui, text = 'Stream on/off').place(x=20,y=350)

#Measurements block
lblMeasHead = Label(mGui, text = "Measurements:", font=("Helvetica", 12, "underline")).place(x=320,y=160)
lblDistanceHead = Label(mGui, text = "Distance:").place(x=320,y=190)
lblDistanceVal = Label(mGui, text = " x cm").place(x=380,y=190)
lblVelocityHead = Label(mGui, text = "Velocity:").place(x=320,y=210)
lblVelocityVal = Label(mGui, text = " x m/s").place(x=380,y=210)

#Send command block
lblCmd = Label(mGui, text = "Enter Command").place(x=330,y=295)
edtCmd = Entry(mGui,textvariable=cmdText).place(x=320,y=320)
btnSendCmd = Button(mGui, text = 'Send Command').place(x=330,y=345)



mGui.mainloop()

1 个答案:

答案 0 :(得分:1)

问题是您正在创建btnConnect作为 -

btnConnect = Button(mGui, text = "Connect", command = Connect).place(x=20,y=70)

.place()方法不返回创建的Button对象(它实际上由Button()返回),它不会返回任何内容,因此您获得NonebtnConnect,这会导致您遇到的问题。您应该将.place()移动到下一行。示例 -

btnConnect = Button(mGui, text = "Connect", command = Connect)
btnConnect.place(x=20,y=70)

以便btnConnect正确指向创建的Button对象。

您当前正在创建上述所有小部件(立即调用.place()),因此如果您稍后再次尝试访问这些小部件,则会遇到同样的问题。而且很可能您需要对以后希望能够访问的所有小部件进行类似的更改。