0

第一个问题是,当我单击“+ $16”按钮时,它没有显示增加,尽管您可以在关闭窗口并在 Python Shell 中输入钱后看到它。第二个问题是,在我添加了那些sticky=SEsticky=SW窗口后,根本不会出现(没有错误消息)。

# money adder
import sys
from tkinter import *
import random

root = Tk()
root.geometry('360x160+800+200')
root.title('app')

money = 100

def addMoney():
    global money
    money = money + 16

def end():
    global root
    root.destroy()

appTitle = Label(root,text='Money Adder',font='Verdana 31',fg='lightblue').pack()
budget = Label(root,text='Budget: $'+str(money),font='Arial 21',fg='green').pack()
moneyButton = Button(root,text='+ $16',width=17,height=2,command=addMoney).grid(sticky=SW)
endButton = Button(root,text='Quit',width=5,height=2,command=end).grid(sticky=SE)

root.mainloop()
4

2 回答 2

1

您根据;中的变量存储一个字符串 标签不会为您保留对变量的引用。moneybudget Labelmoney

每次调用addMoney函数时只需设置标签值:

def addMoney():
    global money
    money = money + 16
    budget.set('$' + str(money))
于 2013-03-30T14:38:09.737 回答
1

First of all, you are storing the return value of grid or pack, which is always None, instead of the reference to the widgets. Besides, you shouldn't use both geometry managers at the same time (if you are new to Tkinter, I'd suggest grid instead of pack).

To update the text of the widget, you have to use config with the text keyword or budget['text']:

budget = Label(root,text='Budget: $'+str(money),font='Arial 21',fg='green')
budget.pack()

def addMoney():
    global money
    money += 16
    budget.config(text='Budget: $'+str(money))

moneyButton = Button(root,text='+ $16',width=17,height=2,command=addMoney)
于 2013-03-30T23:17:06.230 回答