Create Data Entry Window with Tkinter - python

I'm a complete novice when it comes to using Tkinter. I would like to create a function that pops up a window from the main one and asks a user to input some data. They will then click ok and the data will be returned.
The problem I'm having is that I want the my function to pause until this OK button is pressed so it will actually return values instead of empty strings. So far I have the code below.
def enterData(self, *arg):
top = self.top = Toplevel(self)
top.title("Data Entry")
label = []
self.entry = []
for i in range(0, len(arg)):
label.append(Label(top, text=arg[i]))
label[-1].grid(row=i, column=0)
self.entry.append(Entry(top))
self.entry[-1].grid(row=i, column=1)
ok = Button(top, text ="Ok", command = ??Pause??)
ok.grid(row = len(arg), column =0)

Related

When the user write the first name and the last name boxs I want it to get print it in cell using tkinter and python-docx, how can I do that?

I have a program for generating word document using docx-python and I want to design a GUI using tkinter. So, when I enter,for example, the name I want that be print it in the word document in a table, how can I code for such thing ?
root = Tk()
root.geometry('500x500')
root.title("Registration")
label_1 = Label(root, text="FullName",width=20,font=("bold", 10))
label_1.place(x=80,y=130)
entry_1 = Entry(root)
entry_1.place(x=240,y=130)
root.mainloop()
document = Document()
t = document.add_table(rows=3, cols=2, style='TableGrid')
for row in t.rows:
row.height = Inches(0.4)
cell = t.cell(0, 0)
cellp=cell.paragraphs[0]
#here where I want the name get print it
cellp.text='Name : '
cellp.add_run(FullName)
First of all, you need to add button to the GUI because nothing is going to be executed after root.mainloop() without an event. So, let's add a button:
add_btn = Button(root)
add_btn["text"] = "Add name"
add_btn["command"] = add_to_document
add_btn.place(x=240,y=160)
In the example above add_btn will call add_to_document function whenever "Add name" is clicked.
This is where you need to have your document logic.
Here is a working example with a button and a function that prints contents of the text field when this button is pressed.
def add_to_document():
print("Adding " + entry_1.get())
from tkinter import *
root = Tk()
root.geometry('500x500')
root.title("Registration")
label_1 = Label(root, text="FullName",width=20,font=("bold", 10))
label_1.place(x=80,y=130)
entry_1 = Entry(root)
entry_1.place(x=240,y=130)
# Adding a button
add_btn = Button(root)
add_btn["text"] = "Add name"
add_btn["command"] = add_to_document
add_btn.place(x=240,y=160)
root.mainloop()
There are other ways to do it and also a lot better ways to organize things. I suggest giving https://docs.python.org/3/library/tkinter.html a read.
They have a "hello world" example you can draw some inspiration from. https://docs.python.org/3/library/tkinter.html#a-simple-hello-world-program

How do I assign a function to a button so that when it clicks, it displays a string onto a Text() window?

I am trying to make a GUI program where I assign a function to a button so that when pressed it returns a text. However, I am having trouble doing so.
from tkinter import *
class PayrollSummary:
def __init__(pay):
window = Tk()
window.title("Employee Payroll")
#Add Frame 1
frame1 = Frame(window)
frame1.pack()
#Add ReadFile Button
btReadFile = Button(frame1, text = "Read File")
#Add ShowPayroll Button
btShowPayroll = Button(frame1, text = "Show Payroll") #When I press the button "Show Payroll", I want it to display a text in the textbox in the frame below. I tried command = printPayroll but i dont think its working :(
#printPayroll <- use this function to do so
#Formatting
btReadFile.grid(row = 1, column = 2, sticky="w")
btShowPayroll.grid(row = 2, column = 2, sticky="w")
#Text Window
text = Text(window)
text.pack()
text.insert(END, "text displayed from btShowPayroll") #when btShowPayroll is pressed I want it to display text here!
window.mainloop()
PayrollSummary()
You need to add a command to the button click and move text.insert into a new function, as follows:
from tkinter import *
class PayrollSummary:
def __init__(self):
window = Tk()
window.title("Employee Payroll")
#Add Frame 1
frame1 = Frame(window)
frame1.pack()
#Add ReadFile Button
btReadFile = Button(frame1, text = "Read File")
#Add ShowPayroll Button
btShowPayroll = Button(frame1, text = "Show Payroll", command = self.printPayroll) #When I press the button "Show Payroll", I want it to display a text in the textbox in the frame below. I tried command = printPayroll but i dont think its working :(
#printPayroll <- use this function to do so
#Formatting
btReadFile.grid(row = 1, column = 2, sticky="w")
btShowPayroll.grid(row = 2, column = 2, sticky="w")
#Text Window
self.text = Text(window)
self.text.pack()
window.mainloop()
def printPayroll(self):
self.text.insert(END, "text displayed from btShowPayroll \n") #when btShowPayroll is pressed I want it to display text here!
PayrollSummary()
I have solved your problem.
To do this make a method/function of the PayrollSummary class called 'printpayroll' and make it insert the text 'text displayed from btShowPayroll' into the text box. Make the command of the button 'lambda:self.printpayroll()' so that it runs the method/function.
from tkinter import *
class PayrollSummary:
def __init__(self):
window = Tk()
window.title("Employee Payroll")
#Add Frame 1
self.frame1 = Frame(window)
self.frame1.pack()
#Add ReadFile Button
self.btReadFile = Button(self.frame1, text = "Read File")
#Text Window
self.text = Text(window)
self.text.pack()
#Add ShowPayroll Button
self.btShowPayroll = Button(self.frame1, text = "Show Payroll", command = lambda:self.printpayroll()) #When I press the button "Show Payroll", I want it to display a text in the textbox in the frame below. I tried command = printPayroll but i dont think its working :(
#printPayroll <- use this function to do so
#Formatting
self.btReadFile.grid(row = 1, column = 2, sticky="w")
self.btShowPayroll.grid(row = 2, column = 2, sticky="w")
window.mainloop()
def printpayroll(self):
self.text.insert(END, "text displayed from btShowPayroll") #when btShowPayroll is pressed I want it to display text here!
PayrollSummary()
This code creates this window when run:
This is what happens when the 'Show Payroll' button is clicked:
As you can see, what you wanted to happen happened. The text is outputted onto the screen. This happens because the text is inserted into the text box.
Some recommendations:
I recommend you create the window of the program outside of the class because it would be better to make your program only have one window and then multiple frames for each GUI screen of the program.
I recommend adding self. before a lot of the tkinter widgets you created in your class so that they are created as attributes of objects that are created as instantiations of the class.
I recommend you change the code that runs the class to:
PayrollSummaryScreen = PayrollSummary()
I would do this so that the 'PayrollSummaryScreen' object is created and that each of the object's attributes that are created. e.g. frame1, btReadFile, btShowPayroll and text can be accessed using the object. For example you could hide the text if you wanted to, from outside of the class using:
PayrollSummaryScreen.text.pack_forget()
This could be useful for you in the future, for example if you need to hide the Payroll Summary screen and by hiding the 'text' text box and the 'Read File' and 'Show Payroll' buttons, you could hide the frame1 attribute of the object. This would therefore hide the frame's child-widgets which are the 'text' text box and the 'Read File' and 'Show Payroll' buttons.
You could hide the frame1 attribute of the payroll summary screen object using:
PayrollSummaryScreen.frame1.pack_forget()
If you were to take on these recommendations, this would be the code:
from tkinter import *
window = Tk()
window.title("Employee Payroll")
class PayrollSummary:
def __init__(self):
#Add Frame 1
self.frame1 = Frame(window)
self.frame1.pack()
#Add ReadFile Button
self.btReadFile = Button(self.frame1, text = "Read File")
#Text Window
self.text = Text(window)
self.text.pack()
#Add ShowPayroll Button
self.btShowPayroll = Button(self.frame1, text = "Show Payroll", command = lambda:self.printpayroll()) #When I press the button "Show Payroll", I want it to display a text in the textbox in the frame below. I tried command = printPayroll but i dont think its working :(
#printPayroll <- use this function to do so
#Formatting
self.btReadFile.grid(row = 1, column = 2, sticky="w")
self.btShowPayroll.grid(row = 2, column = 2, sticky="w")
window.mainloop()
def printpayroll(self):
self.text.insert(END, "text displayed from btShowPayroll") #when btShowPayroll is pressed I want it to display text here!
PayrollSummaryScreen = PayrollSummary()
I hope this extra information helps!

Python Tkinter label not destroying

So I'm attempting to make a program with tkinter, and so far, things have gone somewhat as hoped, and I nearly achieved what I wanted.
But I've got a problem with destroying labels.
from tkinter import *
root = Tk()
root.geometry("500x500")
def controleerAntwoord(gekozenHeld, submit, eersteHintButton):
antwoord = entry.get()
if antwoord == gekozenHeld:
submit.destroy()
eersteHintButton.destroy()
eersteHint("destroy", button)
startspel()
def eersteHint(superheldHint, button):
hintTextLabel = Label(root, text = "First hint: ")
hintLabel = Label(root, text = superheldHint)
if superheldHint != "destroy":
hintTextLabel.pack()
hintLabel.pack()
button.destroy()
if superheldHint == "destroy":
hintTextLabel.destroy()
hintLabel.destroy()
def startspel():
entry.delete(0, 'end')
gekozenHeld = "test"
superheldHint1 = 'hey'
eersteHintButton = Button(root, text = "Give First Hint", command = lambda: eersteHint(superheldHint1, eersteHintButton))
submit = Button(root, text = "Submit Answer",foreground = "blue", command = lambda: controleerAntwoord(gekozenHeld, submit, eersteHintButton))
eersteHintButton.pack(side = BOTTOM)
entry.pack(side = BOTTOM)
submit.pack(side = BOTTOM, pady = 20)
def start_up():
name = entry.get().strip()
if name != "":
button.destroy()
giveName.destroy()
startspel()
giveName = Label(root, text="Insert your name: ")
entry = Entry(root)
button = Button(root, text="Enter", command=start_up)
entry.pack()
button.pack()
root.mainloop()
This is my current code so far, I know it looks big, but a lot of it can be ignored for this question.
As to how the program works, you enter your name and get taken to the next window.
There you can press the submit button and enter some text, as well as asking for a hint.
When you press the hint button, you get some text on the screen, and when you submit the correct answer, which in this case, is "test", the text should disappear. But it does not.
Any ideas on what I'm doing wrong?
The problem is that you're using a local variable, but expecting that local variable to somehow be remembered the second time you call the function. All your code does is create a label and then immediately destroy the one it just created. If you want it to destroy the one created earlier, you'll have to store that in a global variable.

Tkinter remove/overwrite elements from Frame

I created a button that retrieves a list from a DataFrame based on some input from a text field. Everytime the button is pressed, the list will be refreshed. I output the list (as an OptionMenu) in a separate Frame (outputFrame). However, every time I press this button, a new OptionMenu is added to the Frame (instead of overwriting the previous one). How can I make sure that the content of 'ouputFrame' is overwritten each time I press the button?
# start
root = Tkinter.Tk()
# frames
searchBoxClientFrame = Tkinter.Frame(root).pack()
searchButtonFrame = Tkinter.Frame(root).pack()
outputFrame = Tkinter.Frame(root).pack()
# text field
searchBoxClient = Tkinter.Text(searchBoxClientFrame, height=1, width=30).pack()
# function when button is pressed
def getOutput():
outputFrame.pack_forget()
outputFrame.pack()
clientSearch = str(searchBoxClient.get(1.0, Tkinter.END))[:-1]
# retrieve list of clients based on search query
clientsFound = [s for s in df.groupby('clients').count().index.values if clientSearch.lower() in s.lower()]
clientSelected = applicationui.Tkinter.StringVar(root)
if len(clientsFound) > 0:
clientSelected.set(clientsFound[0])
Tkinter.OptionMenu(outputFrame, clientSelected, *clientsFound).pack()
else:
Tkinter.Label(outputFrame, text='Client not found!').pack()
Tkinter.Button(searchButtonFrame, text='Search', command=getOutput).pack()
root.mainloop()
We can actually update the value of the OptionMenu itself rather than destroying it (or it's parent) and then redrawing it. Credit to this answer for the below snippet:
import tkinter as tk
root = tk.Tk()
var = tk.StringVar(root)
choice = [1, 2, 3]
var.set(choice[0])
option = tk.OptionMenu(root, var, *choice)
option.pack()
def command():
option['menu'].delete(0, 'end')
for i in range(len(choice)):
choice[i] += 1
option['menu'].add_command(label=choice[i], command=tk._setit(var, choice[i]))
var.set(choice[0])
button = tk.Button(root, text="Ok", command=command)
button.pack()
root.mainloop()

Why Won't My Button Be Displayed??

#Last one Looses (II)
from tkinter import *
from tkinter import ttk
root = Tk()
#window
root.title("Last one Looses Mark II")
#Counters Entry
counters = StringVar()
countersL = Label(root, text = "How many counters do you want to play with (10-50)")
countersL.pack(side = LEFT)
countersE = Entry(root, textvariable = counters, bd = 5)
countersE.pack(side = RIGHT)
#Function to process this
def countersinput():
no_counters = int(input(counters.get()))
no_counters = int(input(counters.get()))
#Submit Button
countersB = Button(root, text = "Submit", command = countersinput)
countersB.pack(side = BOTTOM)
#Making sure the counters are between 10-50
while no_counters > 50 or no_counters < 10:
Error = Message(root, text="You need to pick between 10 and 50 counters...")
Error.pack()
counters = StringVar()
countersL = Label(root, text = "How many counters do you want to play with (10-50)")
countersL.pack(side = LEFT)
countersE = Entry(root, textvariable = counters, bd = 5)
countersE.pack(side = RIGHT)
def countersinput():
no_counters = int(input(counters.get()))
countersB = Button(root, text = "Submit", command = countersinput)
countersB.pack(side = BOTTOM)
#Sucess Message
Sucess = Message(root, text=("You are playing with",no_counters,"counters"))
root.mainloop()
Whenever I run it in IDLE the tkinter window does not come up and when I run it into the command line (python one...) it displays the window but with no "submit" button.
I'm really confused please help!
First off, do you realize that your GUI program is asking for input from the command line, and that you're doing that before creating the submit button? That's the reason why the submit button is not showing up. If you're writing a GUI program, you should not be trying to read input from the command line.
If you enter a number between 10 and 50 from the terminal, your code should display a window. However, if you enter a number outside that range, nothing will ever show because of the while no_counters ... loop. That loop will run infinitely, preventing any other interaction with the GUI, and preventing any other widgets from showing up.

Categories

Resources