So! I take an input into an entry box in tkinter, and when the user clicks submit, I want a function to run. Example of my code is below - error is that 'getUsername is not defined'. How can I fix this? Where should I be defining my function?
import tkinter as tk
from tkinter import ttk
class Window(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('1000x500 120 250')
#creates entry button
entry_button = ttk.Button(self, text = "Enter", command = Login)
entry_button.pack()
#creates username entry box
userName_entry = ttk.Entry(self, textvariable = userName)
userName_entry.pack()
openingWin = Window()
openingWin.mainloop()
def Login:
userName = userName_entry.get()
userName_entry.config(state = "disabled")
print(userName)
CodePudding user response:
this is an example of tkinter buttons
import tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
root.title("menu")
frame.pack()
closemenubutton = tk.Button(frame,
text="close menu",
command=root.destroy)
closemenubutton.pack(side=tk.RIGHT)
root.mainloop()
if you need to run something else while its running do this:
import threading
import time
import tkinter as tk
def demo():
root = tk.Tk()
frame = tk.Frame(root)
root.title("menu")
frame.pack()
closemenubutton = tk.Button(frame,
text="close menu",
command=root.destroy)
closemenubutton.pack(side=tk.RIGHT)
root.mainloop()
threading.Thread(target=demo).start()
while True:
time.sleep(3)
print("replace this line and the two above with the rest of your code")
The button function creates a button. You have 3 main parameters the frame parameter is just the frame. The text parameter is what the button will say. The command parameter is assigned a function. When your button is pressed it should run the function .pack() inserts the button into the gui
CodePudding user response:
give this a try
import tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
def do_something_with_usr_name(name):
print(name)
# ^ replace this with your code. name should be a string containing the username
# create the window
root.title("menu")
frame.pack()
# Make a label telling the user what to do
howto = tk.Label(
root,
text="put username below then press button")
# create a writeable box for the name
box_input = tk.Text(root,
height=1,
width=49)
# create the button that gets the name and runs function
output = tk.Button(root,
text="button",
command=lambda: do_something_with_usr_name(str(box_input.get("1.0", 'end-1c'))))
# allows func parameters ^ run the function ^ ^ get the text inside the box ^
# insert them all into the frame
howto.pack(side=tk.TOP)
box_input.pack(side=tk.TOP)
output.pack(side=tk.BOTTOM)
root.mainloop()