I'm trying to get a list of files from an os.listdir command to print into a tkinter label. I have tried a few workarounds, nothing of which has worked out for me.
def booth_bcode_test_window():
booth_bcode_test_window = tk.Toplevel(MainMenu, width=print_width, height=print_height)
booth_bcode_test_window.title("BARCODE TEST")
print_frame = tk.Frame(booth_bcode_test_window, bg='black', bd=5)
print_frame.place(relx=0.5, rely=0.1, relwidth=0.9, relheight=0.8, anchor='n')
print_label = tk.Label(print_frame, bg='gray', font=('courier new',18))
print_label.place(relwidth=1, relheight=1)
confirm_button = tk.Button(booth_bcode_test_window, text="Rename Files", width=10, command=test_click)
confirm_button.place(relx=0.5, rely=0.93, anchor='n')
cancel_button = tk.Button(booth_bcode_test_window, text="Cancel", width=10, command=booth_bcode_test_window.destroy)
cancel_button.place(relx=0.62, rely=0.93, anchor='n')
test_button_tbar = tk.Button(booth_bcode_test_window, text="Run Test", width=10, command=print_test)
test_button_tbar.place(relx=0.38, rely=0.93, anchor='n')
What I'm looking for is to be able to effectively have the function run when the button is clicked, printing the results in the label.
print_label = tk.Label(print_frame, text="this works if I want to type soemthing in" bg='gray', font=('courier new',18))
However, if I'm to use something like this:
print_label = tk.Label(print_frame, text=test_function, bg='gray', font=('courier new',18))
or:
print_label = tk.Label(print_frame, text=test_function(), bg='gray', font=('courier new',18))
I can't get the results of those functions to print into the predefined area I've created for the label.
I have defined those functions, it's a GUI menu with a few windows and all the button clicks etc work fine - I'm just trying to get my info displayed and can't seem to get it up there.
I would like, for example, I am trying to list filenames in a certain directory, so I have defined a listdir function that prints the files in the given directory.
When the button is clicked, the files print in the python window just fine, but as soon as I try to have those results printed in the label window, it won't work.
I have tried using the get command, however, it could be a result of me not using that properly. as it says the function has no get attribute.
I have updated trying to get the results to show in a message box, as after further research - to get a list to show this was the advised way:
def print_filenames():
for f in sorted(os.listdir(ImageDirBT)):
print(f)
def test_function():
print_filename_test.set("File list...")
def confirm_function():
print_filename_test.set("Renaming the files...")
def bcode_test_window():
bcode_test_window = tk.Toplevel(MainMenu, width=print_width,
height=print_height)
bcode_test_window.title("BARCODE TEST")
print_frame = tk.Frame(bcode_test_window, bg='black', bd=5)
print_frame.place(relx=0.5, rely=0.1, relwidth=0.9, relheight=0.8, anchor='n')
print_text = tk.Message(print_frame,
bg='gray',textvariable=print_filename_test, anchor='nw', font=('courier new',11), width=1100)
print_text.place(relwidth=1, relheight=1)
confirm_button = tk.Button(bcode_test_window, text="Rename Files", width=10, command=lambda: confirm_function())
confirm_button.place(relx=0.5, rely=0.93, anchor='n')
cancel_button = tk.Button(bcode_test_window, text="Cancel", width=10, command=bcode_test_window.destroy)
cancel_button.place(relx=0.62, rely=0.93, anchor='n')
test_button_tbar = tk.Button(bcode_test_window, text="Run Test", width=10, command=lambda: test_function())
test_button_tbar.place(relx=0.38, rely=0.93, anchor='n')
So I can get the buttons to change the text in the messagebox. What I'm looking to do is have the results of print_filenames(): appear in the messagebox line for line. Scrollable if the results don't fit on screen.
You have to get strings from os.listdir() and concatenate in one text and then put in Label or Message
filenames = sorted(os.listdir(ImageDirBT))
text = "\n".join(filenames)
#label['text'] = text # change text in Label
print_filename_test.set(text) # change text in Message
Minimal working example
import os
import tkinter as tk
def get_filenames():
filenames = sorted(os.listdir('.'))
text = "\n".join(filenames)
label['text'] = text # change text in label
root = tk.Tk()
label = tk.Label(root) # empty label
label.pack()
tk.Button(root, text="OK", command=get_filenames).pack()
root.mainloop()
Related
I am attempting to open a new window when the New Window button is pressed in the main "root" window. This currently works and does indeed open a second window. In the second window I want to ask the user for an input and then this input will be turned into a list of strings.
An example input would be "Amy, Bob, Carl". The expected output would be ['Amy', 'Bob', 'Carl'] but currently the program just returns [''].
My current code is:
from tkinter import *
root = Tk()
root.title("Welcome screen")
root.geometry("300x300")
def open_new_window():
top = Toplevel()
top.title("second window")
entities = Entry(top)
entries = entities.get().split(", ")
entities.pack()
entities.focus_set()
print(entries)
sub_button = Button(top, text="Submit", command= ?)
sub_button.pack(pady=20)
close_btn = Button(top, text="Close", command=top.destroy)
close_btn.pack()
open_button = Button(root, text="New Window", command=open_new_window)
open_button.pack(pady=20)
exit_button = Button(root, text="Close", command=root.destroy)
exit_button.pack(pady=20)
root.mainloop()
I am new to Tkinter and I am unsure why this is happening. I'm sure it's a simple silly mistake but I can't find where I am going wrong. I also am unsure as to whether I need a Submit button as I don't know what command should be passed to it.
Any advice is appreciated. Please let me know if any additional information is required.
First, we will understand why you got a empty list: your code is executed sequentially, so when you do the entities.get() you haven't yet written anything nor pressed "Submit", i.e., you want to read the entry box once you press the "Submit", not earlier, for that reason, you have the command = ?.
As I am aware, you have mainly 2 options:
Get the text from the button itself
Create a variable linked to the entry box and read this
Method 1: read the data from the entry
from tkinter import *
root = Tk()
root.title("Welcome screen")
root.geometry("300x300")
def do_stuff(entry):
print(entry.get())
def open_new_window():
top = Toplevel()
top.title("second window")
entities = Entry(top)
entities.pack()
entities.focus_set()
sub_button = Button(top, text="Submit", command= lambda: do_stuff(entities))
sub_button.pack(pady=20)
close_btn = Button(top, text="Close", command=top.destroy)
close_btn.pack()
open_button = Button(root, text="New Window", command=open_new_window)
open_button.pack(pady=20)
exit_button = Button(root, text="Close", command=root.destroy)
exit_button.pack(pady=20)
root.mainloop()
Method 2: link a variable
from tkinter import *
root = Tk()
root.title("Welcome screen")
root.geometry("300x300")
def do_stuff(text_entry):
print(text_entry.get())
def open_new_window():
top = Toplevel()
top.title("second window")
text_entry = StringVar()
entities = Entry(top, textvariable = text_entry)
entities.pack()
entities.focus_set()
sub_button = Button(top, text="Submit", command= lambda: do_stuff(text_entry))
sub_button.pack(pady=20)
close_btn = Button(top, text="Close", command=top.destroy)
close_btn.pack()
open_button = Button(root, text="New Window", command=open_new_window)
open_button.pack(pady=20)
exit_button = Button(root, text="Close", command=root.destroy)
exit_button.pack(pady=20)
root.mainloop()
The main advantage in this last approach is that you can play with the text before and after the entry is built.
so i was trying to make a python calculator, that opens like a window, but before the calculations i was trying to make it display the numbers that i clicked, everything was normal, the append, the list, everything was normal until it had to display the actual numbers, where it displays nothing, i tried to make change the label to "hi" for example to see if the problem is with the list, but nothing is being displayed, can someone help me get numbers to be displayed in the "results" area? here is my code:
root = tk.Tk()
color = '#263D42'
numbers = []
Background = tk.Canvas(root, height=600, width=601, bg=color)
Background.pack()
resultBack = tk.Canvas(root, height=150, width=400, bg="#E4E0E0")
resultBack.place(x=50, y=1)
root.title('Calculator')
root.iconphoto(False, tk.PhotoImage(file='plus.ico'))
root.resizable(width = False, height = False)
root.geometry("500x600")
for number in numbers:
label = tk.Label(root, text="hi", bg="black")
label.pack()
frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1) #frame
def addOne():
for widget in frame.winfo_children():
widget.destroy()
numbers.append('1')
for number in numbers:
print(number)
label = tk.Label(root, text=number, bg="black")
label.pack()
print(numbers)
one = tk.Button(root, text="1", padx=10, pady=5, fg="#000000", bg="#ffffff", command=addOne)
one.place(x=30, y=30)
root.mainloop()
You should not be creating and deleting your labels like that; you can just change them.
Maybe try something like this:
import tkinter as tk
root = tk.Tk()
numbers = []
root.title('Calculator')
root.resizable(width = False, height = False)
root.geometry("500x600")
label_text = tk.StringVar()
label_text.set('hi')
label = tk.Label(root, textvariable=label_text)
label.pack()
frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1) #frame
def addOne():
numbers.append(1)
work = ""
for i in numbers:
work+=str(i)
label_text.set(work)
one = tk.Button(root,
text="1",
padx=10,
pady=5,
fg="#000000",
bg="#ffffff",
command=addOne)
one.place(x=30, y=30)
root.mainloop()
That should get the numbers showing up. StringVars are your friend for these sorts of things. As you update them, tk automatically updates the widget they are attached to.
From here, you will probably want to move things around to look better etc. and you probably don't want to have to add a method for each button (addTwo, addThree, addFour etc.) Let us know if you need more help.
I am a beginner programmer and I am trying to solve a very small problem.
I want to make a GUI which has 2 buttons namely, Print and Clear.
I tried my best but cant solve it yet. Wanted Help....
Here is my code( ignore neatness ):
from tkinter import *
main = Tk()
main.geometry("200x200")
global buttonstate
def change():
buttonstate = True
return buttonstate
button1 = Button(main, text="Button", command=change)
if buttonstate==True:
global label
label = Label(main, text= "this works")
elif buttonstate==False:
pass
button2 = Button(main, text="clear", command=lambda: label.pack_forget())
button1.pack()
button2.pack()
label.pack()
main.mainloop()
I am unable to do all the thing in a loop and also to print the statement when the button is clicked...
Thanks.
Here is the GUI with two buttons and a label,
from tkinter import *
main = Tk()
# label where you will print text
text_label = Label(main, width=20)
text_label.grid(row=0, columnspan=2, padx=8, pady=4)
# function to print text in label
def print_text():
# the message you want to display
your_text = "Some message.."
# update the text of your label with your message
text_label.config(text=your_text)
# function to clear text in label
def clear_text():
# clear the label text by passing an empty string
text_label.config(text='')
# print button
# command option is the function that you want to call when the button is pressed
print_btn = Button(main, text='Print', command=print_text, width=8)
print_btn.grid(row=1, column=0, padx=8, pady=4)
# clear button
clear_btn = Button(main, text='Clear', command=clear_text, width=8)
clear_btn.grid(row=1, column=1, padx=8, pady=4)
main.mainloop()
Output GUI
Click Print button to print message
Click Clear button to clear message
I have commented each segment of the code. Hope you understand
def name_label_manager(event):
name = name_entry.get()
label_name = Label(root, text="Name: " + name)
label_name.grid(row=10, column=1, sticky=W)
label_name.delete(0, "end")
def description_label_manager(event):
description1 = description.get()
descrpt = Label(root, text="Description: " + description1)
descrpt.grid(row=9, column=1, sticky=W)
descrpt.delete(0, "end")
i am calling them like this:
button_get = Button(root, text="Submit")
button_get.bind("<Button-1>", description_label_manager,name_label_manager)
button_get.grid(row=2, column=8)
i dont know if this i right but i am calling them with button
for some reason the desctription_label_manager label will show, but the name label wont
As Bryan Oakley pointed out, labels do not have a delete method, Entry Listbox do, but not labels
More so, you can think of tkinter widgets as images drawn on your screen, for these images to display text they must have variables associated with them, here we create some StringVar() variables and assign them to the Entry which you can then use the get method to get what is currently stored in them.
You can add a command argument to a Button to call a function, that should do in this your case.
Check out the code below to understand what I just explained above
import tkinter as tk
def name_label_manager(event=None):
name = name_entry_variable.get()
label_name = tk.Label(root, text="Name: "+name)
label_name.grid(row=10, column=1)
#label_name.delete(0, "end")
description_label_manager()
def description_label_manager(event=None):
description1 = description_entry_variable.get()
descrpt = tk.Label(root, text="Description: "+description1)
descrpt.grid(row=9, column=1)
#descrpt.delete(0, "end")
root=tk.Tk()
name_entry_variable=tk.StringVar()
description_entry_variable=tk.StringVar()
name_entry=tk.Entry(root,textvariable=name_entry_variable,width=10)
name_entry.grid(row=2, column=8)
description_entry=tk.Entry(root,textvariable=description_entry_variable,width=10)
description_entry.grid(row=3, column=8)
button_get = tk.Button(root, text="Submit", command=name_label_manager)
#button_get.bind("<Button-1>", description_label_manager,name_label_manager) command argument of Button should do
button_get.grid(row=4, column=8)
root.mainloop()
I am writing a Python program in TKinter on Ubuntu to import and print
the name of files from particular folder in Text widget.
It is just adding filenames to the previous filnames in the Text
widget, but I want to clear it first, then add a fresh list of filenames.
But I am struggling to clear the Text widget's previous list of
filenames.
Can someone please explain how to clear a Text widget?
Screenshoot and coding is giving below:
import os
from Tkinter import *
def viewFile():
path = os.path.expanduser("~/python")
for f in os.listdir(path):
tex.insert(END, f + "\n")
if __name__ == '__main__':
root = Tk()
step= root.attributes('-fullscreen', True)
step = LabelFrame(root, text="FILE MANAGER", font="Arial 20 bold italic")
step.grid(row=0, columnspan=7, sticky='W', padx=100, pady=5, ipadx=130, ipady=25)
Button(step, text="File View", font="Arial 8 bold italic", activebackground=
"turquoise", width=30, height=5, command=viewFile).grid(row=1, column=2)
Button(step, text="Quit", font="Arial 8 bold italic", activebackground=
"turquoise", width=20, height=5, command=root.quit).grid(row=1, column=5)
tex = Text(master=root)
scr=Scrollbar(root, orient=VERTICAL, command=tex.yview)
scr.grid(row=2, column=2, rowspan=15, columnspan=1, sticky=NS)
tex.grid(row=2, column=1, sticky=W)
tex.config(yscrollcommand=scr.set, font=('Arial', 8, 'bold', 'italic'))
root.mainloop()
I checked on my side by just adding '1.0' and it start working
tex.delete('1.0', END)
you can also try this
According to the tkinterbook the code to clear a text element should be:
text.delete(1.0,END)
This worked for me. source
It's different from clearing an entry element, which is done like this:
entry.delete(0,END) #note the 0 instead of 1.0
this works
import tkinter as tk
inputEdit.delete("1.0",tk.END)
from Tkinter import *
app = Tk()
# Text Widget + Font Size
txt = Text(app, font=('Verdana',8))
txt.pack()
# Delete Button
btn = Button(app, text='Delete', command=lambda: txt.delete(1.0,END))
btn.pack()
app.mainloop()
Here's an example of txt.delete(1.0,END) as mentioned.
The use of lambda makes us able to delete the contents without defining an actual function.
for me "1.0" didn't work, but '0' worked. This is Python 2.7.12, just FYI. Also depends on how you import the module. Here's how:
import Tkinter as tk
window = tk.Tk()
textBox = tk.Entry(window)
textBox.pack()
And the following code is called when you need to clear it. In my case there was a button Save that saves the data from the Entry text box and after the button is clicked, the text box is cleared
textBox.delete('0',tk.END)
I think this:
text.delete("1.0", tkinter.END)
Or if you did from tkinter import *
text.delete("1.0", END)
That should work
A lot of answers ask you to use END, but if that's not working for you, try:
text.delete("1.0", "end-1c")
text.delete(0, END)
This deletes everything inside the text box