1

I would like to generate a window with two buttons, both of which will execute a function and then close the window. However, I can't seem to get the window to close. I've tried rewriting with function several times as per answers to similar questions, but get an error each time. Any help would be greatly appreciated!

import tkinter as tk


class test:
    def __init__(self, root):
       self.text = tk.Label(root, text = 'Question' )
       self.text.pack(side = 'top')
       self.button1 = tk.Button(root, text = 'Yes', command = self.write_right, width = 15)
       self.button1.pack(side='left')
       self.button2 = tk.Button(root, text = 'No', command = self.write_wrong, width = 15)
       self.button2.pack(side='right')
    def write_right(self):
        self.root.destroy()
    def write_wrong(self):
        self.root.destroy()
box = tk.Tk()
functionality = test(box)
box.mainloop()
0

1 Answer 1

2

Adding self.root = root can help:

import tkinter as tk

class test:
    def __init__(self, root):
       self.root = root
       self.text = tk.Label(root, text = 'Question' )
       self.text.pack(side = 'top')
       self.button1 = tk.Button(root, text = 'Yes', command = self.write_right, width = 15)
       self.button1.pack(side='left')
       self.button2 = tk.Button(root, text = 'No', command = self.write_wrong, width = 15)
       self.button2.pack(side='right')
    def write_right(self):
        self.root.destroy()
    def write_wrong(self):
        self.root.destroy()
box = tk.Tk()
functionality = test(box)
box.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.