【问题标题】:If statement with buttons带有按钮的 if 语句
【发布时间】:2021-12-29 10:24:28
【问题描述】:

所以我有一个问题。 我试图用按钮制作一个程序,所以你可以选择带有按钮的东西。 我正在运行 python 3。

我制作了按钮,定制了它们,按钮一切都很好。

def choiceFirst():
    choice = 1
    buttonPressed = True

def choiceSeco():
    choice = 2
    buttonPressed = True

window = Tk()
window.title("Title lol")
icon = PhotoImage(file='download.png')
window.geometry("300x215")
window.iconphoto(True,icon)

button1 = Button(window,
                text="Choice 1",
                command=choiceFirst,
                font=("Arial", 20),
                fg='#00f000',
                bg='white',
                relief=RAISED,
                bd=10,
                padx=20,
                pady=20,
                activeforeground='#00f000',
                activebackground="white",)
button2 = Button(window,
                text="Choice 2",
                command=choiceSeco,
                font=("Arial", 20),
                fg='#00f000',
                bg='white',
                relief=RAISED,
                bd=10,
                padx=15,
                pady=15,
                activeforeground='#00f000',
                activebackground="white",)

button1.pack()
button2.pack()
window.mainloop()

现在我想添加一个 if 语句。类似的东西

if buttonPressed:
   if choice == 1:
      print("choice 1 code here")
   elif choice ==2:
      print("Choice 2 code here")

我尝试添加它,但它不起作用:(

感谢所有帮助!

【问题讨论】:

  • 在您选择的Firse/Seco 函数中,您尝试更改choice - 但此时,这些是局部变量。在这些函数中添加global choice, buttonPressed 作为第一行,以使这些变量成为全局变量并全局更改它们
  • 另外,你在窗口的主循环中。你知道,实际上可以将 "choice 1 code here" 放在 choiceFirst 函数中。

标签: python tkinter tkinter-button


【解决方案1】:

(抱歉英语不好)您必须将按钮的操作放在它们的功能中。

试试这个:

def choiceFirst():
    print("choice 1 code here")

def choiceSeco():
    print("Choice 2 code here")

然后删除 if 语句。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-07
  • 1970-01-01
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 2014-10-16
相关资源
最近更新 更多