Python: Using Tkinter(ttk) to build a simple form

4153 views python
5

Python 3.6

What am I doing wrong here? I would like to give my input value in a variable: after, when i am finish with the Input, i will print the variable in the console.

Thats my Code:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

w = tk.Frame(root)
w.grid(row=0, columnspan=3) 

first_label = tk.Label(w, text="myEntry: ")
myEntry = tk.StringVar()
myEntry_entry = ttk.Entry(w, textvariable= myEntry)
first_label.grid(row=0, column=0, padx=10, sticky=tk.W)
myEntry_entry.grid(row=0, column=1, sticky=tk.W, padx=10)

button1 = tk.Button(w, text='Print in Console')
button1.grid(row=4, columnspan=1, sticky=tk.W)
button1 = tk.Button(self, text="Get", command=self.on_button

myValue = myEntry.get()
print(myValue)

root.mainloop()

answered question

You are getting the entry value at the start of the program and never again. You need to use a function to get value then print when you need it to.

1 Answer

8

What am I doing wrong here?

You stopped in the middle of writing your code and didn't finish:

button1 = tk.Button(self, text="Get", command=self.on_button

Not only did you not finish this line, you didn't define on_button. Other issues include: self undefined; button1 gets initialized to two different buttons; and you're expecting inline code to respond to an event.

Your program starts out fine but then takes a turn towards random bits of pasted code that don't hang together. I would have expected something like:

import tkinter as tk
from tkinter import ttk

def on_button():
    myValue = myEntry.get()
    print(myValue)

root = tk.Tk()

w = tk.Frame(root)
w.grid(row=0, columnspan=3)

first_label = tk.Label(w, text="myEntry: ")
first_label.grid(row=0, column=0, padx=10, sticky=tk.W)

myEntry = tk.StringVar()
myEntry_entry = ttk.Entry(w, textvariable=myEntry)
myEntry_entry.grid(row=0, column=1, sticky=tk.W, padx=10)

button1 = tk.Button(w, text="Print in Console", command=on_button)
button1.grid(row=4, columnspan=1, sticky=tk.W)

root.mainloop()

posted this

Have an answer?

JD

Please login first before posting an answer.