在Tkinter中添加变量
问题描述:
我一直在研究一个将2个数字加在一起的tkinter计算器。我正在计划通过添加一组数字来提高这一点,当你输入一个数字时,将数字乘以那个变量。但是,即使经过广泛的研究,我也找不到一些有关我的特殊问题的帮助。这里是我的代码:在Tkinter中添加变量
from Tkinter import *
root = Tk()
e1 = Entry(root)
e2 = Entry(root)
l = Label(root)
def callback():
total = sum(int(e.get()) for e in (e1, e2))
l.config(text="answer = %s" % total)
b = Button(root, text="add them", command=callback)
for widget in (e1, e2, l, b):
widget.pack()
b.mainloop()
谢谢。
答
变量很容易定义。就像给你的小部件指定一个名字一样,你可以为字符串,列表,字典,元组,数组,整数等等指定一个名字。
例如,如果您想使用变量的值创建一些预定义的倍数,您可以执行类似my_new_var = 2
的操作,然后将my_new_var插入一个函数,该函数将该变量的值乘以任何您想要的值。
下面是一些例子的代码。确保先将2个数字加在一起,然后使用乘以2的按钮。
from Tkinter import *
from functools import total_ordering
root = Tk()
total = 0
my_new_var = 2
e1 = Entry(root)
e1.pack()
e2 = Entry(root)
e2.pack()
l = Label(root)
l.pack()
def callback():
global total
total = sum(int(e.get()) for e in (e1, e2))
l.config(text="answer = %s" % total)
def mulitply_by_two():
global total
total = total * my_new_var
l.config(text="answer = %s" % total)
b = Button(root, text="add them", command=callback)
b.pack()
by_multiple = Button(root, text = "Multiply by {}".format(my_new_var), command = mulitply_by_two)
by_multiple.pack()
b.mainloop()
你的代码看起来不错。你能更好地解释你想要做什么吗?也许有一个例子? – Novel
这是什么问题? –