Reputation: 330
I tried writing a program that tests writing skills. (using tkinter)
For use type in y, press enter, write the sentence you were given press enter again and it outputs the time it took you. This is the part that works.
To add more flexibility I wanted to add a button that shuffles the sentence and gives you a new one. I've tried random.choice
from a list, defining the variable as parameter and am currently stuck at random.randint
. None of them have worked so far. They output a random sentence after launching the code, but the button simply does nothing.
heres the code of the function and further down where the button its used in. if the complete code is necessary to you please just ask for it :D
def change_sentence():
var = random.randint(0,5)
if var == 1:
sentence_var = "thats gonna work"
return sentence_var
if var == 2:
sentence_var = "probably"
return sentence_var
if var == 3:
sentence_var = "i guess"
return sentence_var
if var == 4:
sentence_var = "maybe?"
return sentence_var
if var == 5:
sentence_var = "please??"
return sentence_var
sentence_var = change_sentence()
shuffle_button = Button(root, text="Shuffle", command=change_sentence)
to conclude, i simply look for a way of making my button working.
Upvotes: 0
Views: 325
Reputation: 10590
Having your callback function return a variable doesn't really do anything. Specifically, it won't update the text in your GUI.
You should look into StringVar
and using textvariable
parameter for you text object. Here's a small example. I also cleaned up your if statement:
root = tk.Tk()
class tkApp:
def __init__(self, master):
self.sentence_var = tk.StringVar()
self.change_sentence()
sentence_text = tk.Label(master, textvariable=self.sentence_var)
shuffle_button = tk.Button(master, text="Shuffle", command=self.change_sentence)
sentence_text.pack()
shuffle_button.pack()
def change_sentence(self):
var = np.random.randint(1, 6)
if var == 1:
self.sentence_var.set("thats gonna work")
elif var == 2:
self.sentence_var.set("probably")
elif var == 3:
self.sentence_var.set("i guess")
elif var == 4:
self.sentence_var.set("maybe?")
elif var == 5:
self.sentence_var.set("please??")
myApp = tkApp(root)
root.mainloop()
Upvotes: 1
Reputation: 515
You need to put a print statement inside the function if you just want to print the sentence. Your variable sentence_var will be assigned a string when calling the function but after that the Button will have no effect on it as it is not inside the function.
Upvotes: 1