问题描述
我想要选择不同的“困难”并选择不同的结果,我按开始。 我不能让它工作。我试图在 youtube 上寻找答案,但没有找到任何有用的东西。
import tkinter as tk
from tkinter import messageBox
import random
root = tk.Tk()
root.title("Simple Game")
canvas1 = tk.Canvas(root,width=300,height=300,bg="black")
canvas1.pack()
canvas1.create_text(150,50,text="Simple Game",font="Times",fill="white")
root.resizable(False,False)
exitbutton = tk.Button(root,text="Exit Game",command=root.destroy,fg="black",activebackground="red").place(x=96,y=250)
def startgame():
if DifficultyList == "Difficulty":
messageBox.showinfo("disclaimer","You need to choose a difficulty!")
elif DifficultyList == "Easy":
messageBox.showinfo("Info","You are Now playing on Easy mode!")
startbutton = tk.Button(root,text="Start",command=startgame,activeforeground="white",activebackground="green").place(x=96,y=150)
canvas1.create_window(150,150,window=exitbutton)
canvas1.create_window(150,window=startbutton)
DifficultyList = (
"Difficulty","Easy","Medium","Hard"
)
variable = tk.StringVar(root)
variable.set(DifficultyList[0])
Difficulty = tk.OptionMenu(root,variable,*DifficultyList).place(x=94,y=100)
root.mainloop()
解决方法
这是tkinter
基础知识的一部分,您需要使用get()
从变量/单选按钮中获取值,并与选项列表中的值(DifficultyList
),所以你的函数应该是:
def startgame():
if variable.get() == DifficultyList[1]: # Check if 2nd item on list is selected
messagebox.showinfo("Info","You are now playing on Easy mode!")
elif variable.get() == DifficultyList[2]:
messagebox.showinfo("Info","You are now playing on Medium mode!")
elif variable.get() == DifficultyList[3]:
messagebox.showinfo("Info","You are now playing on Hard mode!")
else: # If the selection is anything else other than above mentioned,then
messagebox.showinfo("Disclaimer","You need to choose a difficulty!")
请注意我如何更改您的 if
并将其移至 else
,因为它是从列表中选择的唯一语句,因此它是 else
的一部分。是的,您也可以选择任何其他语句作为 else
,但这是唯一一个奇怪的语句,所以我选择了它。
请注意,虽然命名变量要遵循约定,例如列表通常以所有小写字母命名,但类将命名为 PascalCase 并且函数可能使用 camelCase 命名,但通常使用变量都是小写字母。还要检查:Some common naming conventions are for python