0

i have seen and tried the answer in Tkinter StringVar error but it still didnt fix anything, i am making a text based rpg (i'm aware python isn't nescesarily the best for games, and that its probably inconvenient) and im trying to make the an if statement to keep the grammar correct. here is the code so far

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()

Here is the error

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
xXMAZEEXx
  • 13
  • 5

1 Answers1

0

You need to assign your StringVar objects to attributes:

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()
Daniel
  • 42,087
  • 4
  • 55
  • 81