[英]Python Tkinter StringVar issues
I am trying to make a simple calculator for a game I play as a random project. 我正在尝试为作为随机项目玩的游戏制作一个简单的计算器。 I found myself very confused on how to go about doing this;
我发现自己对如何执行此操作感到非常困惑; I want the user to enter a number in the textbox and it will multiply that number by 64000 and display it in a label above.
我希望用户在文本框中输入一个数字,它将数字乘以64000并显示在上方的标签中。 But, I cannot find out anywhere how to do this.
但是,我找不到任何方法。 This is just a small practice thing and im amazed I cannot figure it out.
这只是很小的练习,我很惊讶我无法弄清楚。 Please help meh!
请帮忙! Here is my code:
这是我的代码:
from Tkinter import *
####The GUI#####
root = Tk()
#Title#
root.wm_title("TMF Coin Calculator")
####The Widgets####
a = StringVar()
b = StringVar()
def multiply_a():
d = (int(a) * 64000)
e = str(d)
b.set(e)
b.trace("w", multiply_a)
#Top Label#
top_label = Label(root, fg="red", text="Type the ammount of Coin Stacks you have.")
top_label.grid(row=0, column=0)
#The Output Label#
output_label = Label(root, textvariable=b, width = 20)
output_label.grid(row = 1, column=0)
#User Entry Box#
user_input_box = Entry(root, textvariable=a, width=30)
user_input_box.grid(row=2, column=0)
root.mainloop()
You need to trace
the variable that changes: a
. 您需要
trace
更改的变量: a
。 Then you need to define multiply_a()
to handle an arbitrary number of arguments with *args
(happens to be 3 arguments in this case, but *args
is fine here). 然后,你需要定义
multiply_a()
来处理的带参数的任意数量*args
(恰好是在这种情况下3个参数,但*args
是这里很好)。
Go from: 从...来:
def multiply_a():
d = (int(a) * 64000)
e = str(d)
b.set(e)
b.trace("w", multiply_a)
to: 至:
def multiply_a(*args):
try:
myvar = int(a.get())
except ValueError:
myvar = 0
b.set(myvar * 64000)
a.trace("w", multiply_a)
This will additionally use 0
if the entered value can't be turned into an int
. 如果输入的值不能转换为
int
则将另外使用0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.