【问题标题】:Incrementing variable by 1 when button is pressed按下按钮时变量加 1
【发布时间】:2021-02-16 18:56:19
【问题描述】:

我一直在尝试找出 tkinter,因为我的计算机科学项目需要它,所以我对它还是很陌生,但我正在尝试制作一个按钮,当按下时,变量会增加并输出更改的金额。

这是我尝试过的原始代码:

from tkinter import *

root = Tk()

item_num = 0


def AddButton():
    global item_num
    item_num =+ 1
    item_text = "Item "+ item_num
    item1 = Label(receiptFrame, text=item_text, padx=25, pady=10)
    item1.pack()

addButton = Button(root, text="Add Button", padx=25, pady=25, command=AddButton)
addButton.pack()

receiptFrame = Frame(root, width=70, height=30)
receiptFrame.pack()

root.mainloop

当我按下按钮时,它会出现:

item_text = "项目"+ item_num

TypeError: 只能将 str(不是“int”)连接到 str

我尝试使用我在此处找到的另一个解决方案,使用 IntVar(), set & get 但运行时我得到:

TypeError: 只能将 str(不是“IntVar”)连接到 str

from tkinter import *

root = Tk()

item_num = 0
item_num = IntVar()

def AddButton():
    global item_num
    item_num.set(item_num.get()+1)
    item_num = int(item_num)
    item_text = "Item "+ item_num
    item1 = Label(receiptFrame, text=item_text, padx=25, pady=10)
    item1.pack()

addButton = Button(root, text="Add Button", padx=25, pady=25, command=AddButton)
addButton.pack()

receiptFrame = Frame(root, width=70, height=30)
receiptFrame.pack()

root.mainloop

我也尝试过使用 lambda 将 item_num 作为参数放入函数中,但是当我这样做时,按钮根本无法再次按下,我不确定那里出了什么问题

再次,我不完全确定我在做什么,所以我会很感激任何半初学者的解决方案啊哈 :)

【问题讨论】:

  • 应该是item_num += 1item_text = "Item",item_num
  • 我想你的意思是item_text = "Item "+ str(item_num)

标签: python tkinter button


【解决方案1】:

您正在使用+ 进行连接,这是问题所在,因为+ 的两边都需要是字符串。您还有其他问题,例如:

  • 您使用了=+ 1,表示该值始终为+1(正1),应为+= 1,因此每次增加1。
  • 另外你忘了把()放在mainloop()的末尾。
  • 每次单击按钮时都会创建一个新标签,而不是创建一个标签并更改其文本。

所以最终的格式化代码是:

from tkinter import *

root = Tk()

item_num = 0
def AddButton():
    global item_num

    item_num += 1 # Add current value plus 1
    item_text = "Item"+str(item_num) 
    item1.config(text=item_text) # Change the text of the label
    print(item_text)

item1 = Label(root, padx=25, pady=10) # Make the label for the first time
item1.pack()
# Same code...

root.mainloop() # Important ()

还有其他方法可以使用 write item_text,例如:

item_text = "Item"+str(item_num) # This returns a string
item_text = "Item",item_num # This returns a tuple
item_text = f'Item{item_num}' # This returns a string
item_text = "Item{}".format(item_num) # This returns a string as well

【讨论】:

  • 顺便说一句,您的声明“+ 的两侧都需要相同的type”在技术上是不正确的,因为您可以添加 <int><float> 类型的对象。您还可以在自定义类中定义 __add__ 魔术方法,以便您可以将该类型的对象添加到任何其他类型的对象中。
  • @thelizzard 是的,这是有道理的,我在谈论串联,但在半路忘记了,我的错。
猜你喜欢
  • 2023-03-05
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
  • 1970-01-01
相关资源
最近更新 更多