【问题标题】:How to reuse a Button action如何重用按钮操作
【发布时间】:2023-02-12 04:57:12
【问题描述】:
我试图重用这个按钮的动作,而不是重新调用命令,问题是,在按钮执行第一个“if”语句“y == 1”之后。
现在,而不是访问第二个“if”语句“y == 2”(也就是说,假设程序现在开始,如果我在输入框中输入 1 并单击按钮,程序应该打印“是! ”,然后如果我在输入框中再次输入 2 并单击按钮,程序应该打印“是!是!”,但它会重新启动“def action()”)
如果我使用控制台,我希望它像第二个代码一样运行
from tkinter import *
win = Tk()
def action():
y = x.get()
if y == 1:
print("Yes!")
if y == 2:
print("Yes!Yes!")
elif y == 3:
print("Yes!Yes!Yes!")
else:
print("No")
x = IntVar()
e1 = Entry(win, textvariable = x).grid()
b1 = Button(win, text = "Button", command = action).grid()
win.mainloop()
第二个代码
y = eval(input("Enter a value: "))
if y == 1:
print("Yes")
y = eval(input("Enter a value: "))
if y == 2:
print("Yes!Yes!")
elif y == 3:
print("Yes!Yes!Yes!")
else:
print("No")
【问题讨论】:
标签:
python
python-3.x
tkinter
tkinter-button
【解决方案1】:
放
y = x.get()
clicked = False
后
b1 = Button(win, text = "Button", command = action).grid()
现在,
def action():
if y == 2 and clicked == True:
print("Yes!Yes!")
if y == 3 and clicked == True:
print("Yes!Yes!Yes!")
if y == 1 and clicked == False:
print("Yes!")
clicked = True
如果我很好地理解您的问题,这可能会弹出所需的结果。
【解决方案2】:
海象获救。
代码:
from tkinter import *
win = Tk()
def action():
# y = x.get()
if (y := x.get()) == 1:
print("Yes!")
elif y == 2:
txt= 'Yes!'
print(txt*2)
elif y == 3:
txt = 'Yes!'
print(txt*3)
else:
print("No")
x = IntVar()
e1 = Entry(win, textvariable = x).grid()
b1 = Button(win, text = "Button", command = action).grid()
win.mainloop()
结果:
Yes!
Yes!Yes!
Yes!Yes!Yes!
No
【解决方案3】:
如果我在输入框中输入 1 并单击按钮,程序
应该打印“Yes!”,然后如果我在输入框中再次输入 2 并且
单击按钮,程序应打印“Yes!Yes!”,等等。
海象获救。
代码:
from tkinter import *
win = Tk()
def action():
# y = x.get()
if (y := x.get()) == 1:
print("Yes!")
elif y == 2:
txt= 'Yes!'
print(txt*2)
elif y == 3:
txt = 'Yes!'
print(txt*3)
else:
print("No")
x = IntVar()
e1 = Entry(win, textvariable = x).grid()
b1 = Button(win, text = "Button", command = action).grid()
win.mainloop()
结果:
Yes!
Yes!Yes!
Yes!Yes!Yes!
No