【发布时间】:2020-04-08 09:57:23
【问题描述】:
我正在使用 Tkinter 制作一个愚蠢的计算器,并且我有一个名为“短语”的全局变量。所以基本上,我有按钮(无意义的名称),我只想加/减并打印出句子,例如“香蕉”+“牛奶”=“香蕉牛奶!”但是我很难将用户的输入保存到全局变量“短语”中。以下是我的代码:
from tkinter import *
phrase = ''
# To press any button
def press(item):
global phrase
if item == 'Banana':
phrase = 'This is yellow'
elif item == 'Milk':
phrase = 'This is white'
return equation.set(phrase)
############################### Here is the fucntion adding together
def recipe(item):
global phrase
if item == 'AND':
phrase = phrase + ' ' + str(item)
equation.set(phrase)
# Driver code
if __name__ == '__main__':
# create application window
app = Tk()
# title
app.title("Silly Calculator")
# geometry
app.geometry('290x162')
# background color
app.configure(bg='pink')
equation = StringVar()
windows = Entry(app, textvariable=equation)
windows.grid(columnspan=5, ipadx=100, ipady=10)
equation.set('Listen to your Funculator!')
# Create buttons and other accessories
button1 = Button(app, text='Banana', fg='yellow', bg='purple',
command=lambda: press('Banana'), height=2, width=10)
button1.grid(row=2, column=0, sticky="NSEW")
button2 = Button(app, text='Milk', fg='brown', bg='pink',
command=lambda: press('Milk'), height=2, width=10)
button2.grid(row=2, column=1, sticky="NSEW")
plus = Button(app, text='AND', fg='black', bg='white',
command=lambda: recipe('AND'), height=2, width=10)
plus.grid(row=4, column=0, sticky="NSEW")
# start the GUI
app.mainloop()
所以我尝试将全局变量 phase 设置为列表 [],并可能通过索引号访问。但这不起作用,我只将最后一个用户输入保存到“短语”中。有没有办法可以保存在不同的变量中,例如短语_1、短语_2,以便我可以在以下情况下使用它们:
# This is enter
def recipe(item):
global phrase
if item == 'AND':
phrase = phrase_1 + phrase_2
equation.set(phrase)
像这样?
任何建议将不胜感激!
【问题讨论】:
-
您可以使用
Checkbutton代替Button作为收件人。然后您可以检查哪些收件人被检查并构建所需的配方。 -
谢谢,我不知道检查按钮....!!