为简单的Tkinter程序获取错误

时间:2014-07-14 03:29:12

标签: python tkinter

我一直在尝试使用Tkinter和Python制作一个简单的程序。您所做的只是单击按钮,根据您单击的按钮,它会更新某些标签。这是我的代码:

from tkinter import *

apples = 0
gold = 0

def pick():
    global apples
    apples = apples + 1


def sell():
    global apples
    global gold
    gold = gold + (apples * 10)
    apples = 0

app = Tk()

app.title("Apple Picking Simulator 2014")
app.geometry("400x300+100+60")

label1 = Label(text = "Welcome to Apple Picking Simulator 2014!").pack()
Label().pack()
label2 = Label(text = "Apples: " + apples).pack()
label3 = Label(text = "Gold: " + gold).pack()
button1 = Button(text = "Pick Apple", command = pick).pack()
button2 = Button(text = "Sell Apples", command = sell).pack()

app.mainloop()

现在,每当我尝试运行程序时,我都会收到错误:

TypeError: Can't convert 'int' object to str implicitly

我知道它无法将整数转换为字符串,但我一直在尝试所有内容,而我似乎无法使其工作。是否有一种简单的方法可以在窗口上显示苹果和黄金数字,并在每次点击选择或卖出按钮时更新它们?感谢。

2 个答案:

答案 0 :(得分:0)

尝试将整数连接到字符串是导致错误的原因。您需要使用str functionapplesgold整数变量显式转换为字符串。

替换:

label2 = Label(text = "Apples: " + apples).pack()
label3 = Label(text = "Gold: " + gold).pack()

使用:

label2 = Label(text = "Apples: " + str(apples)).pack()
label3 = Label(text = "Gold: " + str(gold)).pack()

修复源代码:

from tkinter import *

apples = 0
gold = 0

def pick():
    global apples
    apples = apples + 1


def sell():
    global apples
    global gold
    gold = gold + (apples * 10)
    apples = 0

app = Tk()

app.title("Apple Picking Simulator 2014")
app.geometry("400x300+100+60")

label1 = Label(text = "Welcome to Apple Picking Simulator 2014!").pack()
Label().pack()
label2 = Label(text = "Apples: " + str(apples)).pack()
label3 = Label(text = "Gold: " + str(gold)).pack()
button1 = Button(text = "Pick Apple", command = pick).pack()
button2 = Button(text = "Sell Apples", command = sell).pack()

app.mainloop()

答案 1 :(得分:0)

您的问题是您正在尝试连接字符串和整数:

label2 = Label(text = "Apples: " + apples).pack()
label3 = Label(text = "Gold: " + gold).pack()

这会产生错误:

>>> apples = 0
>>> "Apples: ", apples
('Apples: ', 0)
>>> "Apples: " + apples
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> 

以下是您编辑的代码:

from tkinter import *

apples = 0
gold = 0

def pick():
    global apples
    apples = apples + 1


def sell():
    global apples
    global gold
    gold = gold + (apples * 10)
    apples = 0

app = Tk()

app.title("Apple Picking Simulator 2014")
app.geometry("400x300+100+60")

label1 = Label(text = "Welcome to Apple Picking Simulator 2014!").pack()
Label().pack()
label2 = Label(text = "Apples: " + str(apples)).pack()
label3 = Label(text = "Gold: " + str(gold)).pack()
button1 = Button(text = "Pick Apple", command = pick).pack()
button2 = Button(text = "Sell Apples", command = sell).pack()

app.mainloop()
相关问题