0

I'm having trouble learning how to save a textbox input in tkinter as a string variable. This is what I have so far.

from tkinter import messagebox

class Setup:

    def __init__(self):
        
        #layout of setup window
        self.root = tk.Tk()
        self.root.geometry("500x300")
        self.root.title("Setup")

        self.label = tk.Label(self.root, text="Title of next window", font=('Arial', 18))
        self.label.pack(padx=10, pady=10)

        self.textbox = tk.Text(self.root, height=1, font=('Arial', 16))
        self.textbox.pack(padx=50, pady=10)

        self.button = tk.Button(self.root, text="Save", font=('Arial', 18), command=self.save)
        self.button.pack(padx=10, pady=10)

        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)

        self.root.mainloop()

    def on_closing(self):
        if messagebox.askyesno(title="Quit?", message="Do you really want to quit?"):
            self.root.destroy()

    #save the textbox as var title and open counter
    def save(self):
        title = self.textbox.get('1.0', tk.END)
        Counter()

class Counter:
    def __init__(self):
        
        #layout of counter window
        self.root = tk.Tk()
        self.root.geometry("500x300")
        self.root.title(title) 

Setup()

I'm trying to have the textbox contents be the title of the counter window. Can anyone help with this?

livymio
  • 11
  • 3
  • 3
    You should only create one instance of `Tk()` and use `Toplevel()` for any additional windows you need. – Rory Mar 06 '23 at 19:02

3 Answers3

2

You are already storing it in a variable. That variable is out of scope when you use it. So use a global variable:

    def save(self):
        global title
        title = self.textbox.get('1.0', tk.END)
        Counter()

Refer to the chapter on scope in your book or here

Emanuel P
  • 1,586
  • 1
  • 6
  • 15
  • Since the method in question `save` is defined as a method in the `Setup` class, it would be better to use an instance variable, e.g. `self.title`, rather than a global variable. – JRiggles Mar 06 '23 at 20:56
2

Never used global. The correct way is to add data in __init__ parameter

Snippet:

    def save(self):
        
        title = self.textbox.get('1.0', tk.END)
        Counter(title)

class Counter:
    def __init__(self, data):
        
        #layout of counter window
        self.root = tk.Tk()
        self.root.geometry("500x300")
        self.root.title(data) 

Screenshot:

enter image description here

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
0

You could define the variable self.title at the start of your Setup class, and then use this to get your textbox's content:

def save(self):
     self.title = self.textbox.get("1.0", tk.END)
     Counter()
BitPigeon
  • 1
  • 4