我已经看到并尝试了Tkinter StringVar error中的答案,但是它仍然没有解决任何问题,我正在基于文本的rpg(我知道python不一定是游戏的最佳选择,并且它可能很不方便),而我试图制作一个if语句来保持语法正确。这是到目前为止的代码
import tkinter as tk
import random
from tkinter import*
class Nirvana:
def __init__(self, master):
self.master = master
master.title("Nirvana")
happen = StringVar()
self.event = Message(master, textvariable= happen)
self.event.grid(row=0)
self.b1 = Button(master, text= "Continue", command= self.go)
self.b1.grid(row=1)
encounter = StringVar()
enc = encounter.get()
hap = happen.get()
def go(self):
encounter.set(random.choice(hostiles1 + hostiles2))
if (enc[0]) is "a" or "e" or "i" or "o" or "u":
happen.set("You have encountered an", enc)
else:
happen.set("You have encountered a", enc)
d = ("dragon")
w = ("wolf")
o = ("ogre")
hostiles1 = [d, w]
hostiles2 = [o]
root = Tk()
root.geometry("500x500")
my_gui = Nirvana(root)
root.mainloop()
这是错误
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1702, in __call__
return self.func(*args)
File "Tbr.py", line 22, in go
encounter.set(random.choice(hostiles1 + hostiles2))
NameError: name 'encounter' is not defined
答案 0 :(得分:0)
您需要将StringVar对象分配给属性:
import tkinter as tk
import random
class Nirvana:
def __init__(self, master, hostiles1, hostiles2):
self.master = master
self.hostiles1 = hostiles1
self.hostiles2 = hostiles2
master.title("Nirvana")
self.happen = tk.StringVar()
self.event = tk.Message(master, textvariable=self.happen)
self.event.grid(row=0)
self.b1 = tk.Button(master, text="Continue", command=self.go)
self.b1.grid(row=1)
self.encounter = tk.StringVar()
def go(self):
self.encounter.set(random.choice(self.hostiles1 + self.hostiles2))
enc = self.encounter.get()
a = "an" if enc[0] in ("a", "e", "i", "o", "u") else "an"
self.happen.set("You have encountered {} {}".format(a, enc))
def main():
d = "dragon"
w = "wolf"
o = "ogre"
hostiles1 = [d, w]
hostiles2 = [o]
root = tk.Tk()
root.geometry("500x500")
my_gui = Nirvana(root, hostiles1, hostiles2)
root.mainloop()
if __name__ == '__main__':
main()