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
Related
I been searching for methods to copy text to clipboard or copy the results from Tkinter gui but idk if there is a command or something
here is my code for now here the result comes in a messagebox can i copy it to clipboard
import tkinter.messagebox
import string
import random
def qs_msgbbox(): # qs_msgbbox
tkinter.messagebox.showinfo("Info", "For customer support or tip or rating contact:"
"dghaily725#gmail.com\npress the button for generated pass\nmsg will appear then copy\nthe generated password")
def gen_pass(k=9): # gen_pass
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*"
password = ''
for i in range(9):
password += random.choice(char)
tkinter.messagebox.showinfo("Password", password)
root = Tk()
root.title("Password Generator")
lbl1 = Label(root, text="Generate Password", bd=2, relief=SUNKEN, height=5, width=50, bg='black', fg='white')
lbl1.configure(font=(70))
lbl1.grid(row=0, column=2)
lbl2 = Label(root, text='For more information press the Question mark', bd=2, relief=SUNKEN, fg='red')
lbl2.configure(font=(70))
lbl2.grid(row=0, column=0, pady=10)
btn1 = Button(root, text='Press to Generate', height=5, width=50, bg='grey', command=gen_pass)
btn1.configure(font=(70))
btn1.grid(row=1, column=2, padx=460, pady=50)
btn2photo = PhotoImage(file='question.png')
btn2 = Button(root, image=btn2photo, width=30, height=30, command= qs_msgbbox)
btn2.grid(row=0, column=1)
root.mainloop()
and also just a quick small question is it better to use classes or this form
Tkinter does have a function for that, simply just
from tkinter import Tk
root = Tk()
root.clipboard_clear()
root.clipboard_append("Something to the clipboard")
root.update() # the text will stay there after the window is closed
Hope I could help
Greets
The above answer is perfectly fine. Infact its the method to do it. I read the comments, He had mentioned that it could only take in string. That is completely false. It can also take in functions. For example..
import tkinter as tk
root = tk.Tk()
#creating a entry Widget.(Labels are fine as well)
entry = tk.Entry(root)
entry.pack()
#NOW if you want to copy the whole string inside the above entry box after you
typed in #
def copy ():#assign this function to any button or any actions
root.clipboard_clear()
root.clipboard_append(entry.get()) #get anything from the entry widget.
root.mainloop()
Hoping this was helpful
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()
I am trying to create a window with Tkinter but no window is being created and I am not receiving any error codes?
from tkinter import *
def login_window():
window=Tk()
window.title("Login")
info_lbl = Label(window)
info_lbl.grid(row=0, column=1)
username_lbl = Label(window, text='Username')
username_lbl.grid(row=1, column=1)
username_entry = Entry(window, width=10)
username_entry.grid(row=1, column=2)
password_lbl = Label(window, text='Password')
password_lbl.grid(row=2, column=1)
password_entry = Entry(window, width=10, )
password_entry.grid(row=2, column=2)
ok_button = Button(window, text='Login', command = menu_window)
ok_button.grid(row=3,column = 2,sticky =W)
Any help would be great!
Well I think u should add mainloop() inside your function as well as call your login_window something like this-
from Tkinter import *
def login_window():
window=Tk()
window.title("Login")
mainloop()
login_window()
It looks like you never entered the main Tkinter loop. To display that window, you could add this to the bottom of the function:
window.mainloop()
Take a look at this question and the accepted answer for a bit more information on the Tkinter main loop.
Hey guys I have just started learning about GUI's and in particular just started using tkinter. I have spent hours searching forums for what I believe should be an obvious and simple solution and found a few people asking similar questions but i failed to understand the solutions.
Basically I am just trying to get the user to input a letter with an entry widget and display that on a label when the go button is pressed. If anyone could explain to me how to do this I would be extremely grateful.
Here's the code I have written:
#!/usr/bin/env python3
from tkinter import*
from tkinter import ttk
import random
root = Tk()
root.title('test')
frame = ttk.Frame(root, padding='3 3 12 12 ')
frame.grid(column=0, row=0, sticky=(N, W, E, S))
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
letter = StringVar()
def gobutton(*args):
print_label['text'] += letter
print_label = ttk.Label(frame, text="")
print_label.grid(column=1, row=1, sticky=N)
letter_entry = ttk.Entry(frame, width=7, textvariable=letter)
letter_entry.grid(column=1, row=2, sticky=S)
g_button = ttk.Button(frame, width=7, text='GO', command=gobutton)
g_button.grid(column=3, row=3, sticky=S)
for child in frame.winfo_children():
child.grid_configure(padx=5, pady=5)
letter_entry.focus() #WHAT DOES THIS DO?
root.bind('<Return>', gobutton)
root.mainloop()
You should .get() what StringVar contains when button is clicked.
def gobutton(): #if you don't plan to pass any parameters, *args is unnecesarry
print_label['text'] += letter.get()
Also, for this program, using a StringVar a little bit overkill. You can easily go for Entry.get() to get what entry contains. Below code demonstrates how to use get() method with a quite simple(and a little bit dirty) code.
def getMethod():
lbl.configure(text=ent.get())
#or
#lbl["text"] = ent.get()
root = tk.Tk()
tk.Button(root, text="Get Entry", command=getMethod).pack()
ent = tk.Entry(root)
lbl = tk.Label(root, text = "Before click")
lbl.pack()
ent.pack()
root.mainloop()
.focus() is an alias for .focus_set() method.
Moves the keyboard focus to this widget. This means that all keyboard
events sent to the application will be routed to this widget.
I'm new to tkinter and have a rather simple question. I would like to change focus from the first window, root, to the txt window after it pops up. I would also like the "OK" button to be focused as well. Of course, the idea is for the user to just be able to hit enter when they see this error. I'm terribly confused after various attempts with focus(), focus_set(), and takefocus. I'm not finding the documentation for this particularly helpful.
Below is my code:
from tkinter import *
from tkinter import ttk
def close(self):
self.destroy()
def browse(*args):
fileName = filedialog.askopenfilename()
guiInputFile_entry.insert(0, fileName)
return fileName
def formatInput(*args):
if guiInputFile.get()[-4:] != ".txt": #checks for correct file extension (.txt)
txt = Tk()
txt.title("Error")
txtFrame = ttk.Frame(txt, padding="30 30 30 30")
txtFrame.grid(column=0, row=0, sticky=(N,W,E,S))
txtFrame.columnconfigure(0, weight=1)
txtFrame.rowconfigure(0, weight=1)
ttk.Label(txtFrame, text = "Please enter a .txt file.\n").grid(column=2, row=1)
okButton = ttk.Button(txtFrame, text = "OK", command = lambda: close(txt)).grid(column=2, row=2)
return
root = Tk()
root.title("Cost Load Formatter")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N,W,E,S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
guiInputFile = StringVar()
guiInputFile_entry = ttk.Entry(mainframe, width=100, textvariable=guiInputFile)
guiInputFile_entry.grid(column=1, row=2, stick=(W,E))
ttk.Label(mainframe, text="Please enter the full filepath of the .txt file you wish to format:").grid(column=1, row=1)
browseButton = ttk.Button(mainframe, text="Browse...", underline=0, command=browse).grid(column=2, row=2, sticky=W)
formatButton = ttk.Button(mainframe, text="Format", underline=0, command= lambda: formatInput(guiInputFile)).grid(column=1, row=3)
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
guiInputFile_entry.focus()
root.mainloop()
Thank you for any light you can shed.
You're on the right track.
Firstly, you should only ever have one instance of Tk at a time. Tk is the object that controls the tkinter application, it just so happens that it also shows a window. Whenever you want a second window (third, fourth, etc.) you should use Toplevel. You can use it as you have used Tk, just pass it root:
txt = Toplevel(root)
It is just missing things like mainloop.
Secondly grid and pack do not return anything. So for example:
okButton = ttk.Button(txtFrame, text = "OK", command = lambda: close(txt)).grid(column=2, row=2)
Should be:
okButton = ttk.Button(txtFrame, text = "OK", command = lambda: close(txt))
okButton.grid(column=2, row=2)
But you should have been getting an error if that was causing you problems.
So to answer your main question, as you do with the Entry at the bottom you just call focus on the appropriate widget. focus_set does exactly the same, in fact if you look in Tkinter.py you will find focus_set is the name of the method, and focus is just an alias.
This will give the widget focus when the application has focus. If the application is not in focus there are ways to force it into the focus, but it is considered impolite and you should let the window manager control that.
Instead of making a seperate Tk Window, you could use the built in tkmessagebox. This will give the window and OK button focus right out of the box.
Something like this:
tkMessageBox.showinfo("Warning","Please enter a .txt file.")
http://www.tutorialspoint.com/python/tk_messagebox.htm
Also, note I wrote this in Python 2.7, the syntax may be slightly different for Python 3, but the functionality should be the same.