I am stating to develop a program in which you click a button with the text "open" on it, and it will bring up a file selection window using filedialog.askopenfilename, but the button won't appear, and it will automatically bring up the window without the button needing to be pressed. Here is the code:
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Snake converter")
sim = filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
openbutton = Button(root, text = "Open", width = 10, command = sim)
Nowhere in your code you're calling a geometry manager(pack, grid, place etc.) so your button isn't shown. Also filedialog.askopenfilename runs immediately even if it's assigned to an object. I am also unsure that you can call an object as button function. Try the following:
def sim():
filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
openbutton = Button(root, text = "Open", width = 10, command=sim)
openbutton.pack()
root.mainloop()
also your code should look like:
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Snake converter")
def sim():
filedialog.askopenfilename(filetypes = (("Snake files", "*.sim"),("Python Files", "*.py"),("All files", "*.*")))
openbutton = Button(root, text = "Open", width = 10, command=sim)
openbutton.pack()
root.mainloop()
I'd also check frequent questions as a newcomer to tkinter.
Related
I have made a pdf viewer using tkinter. I am wondering if I can let the pdf file 'pop out' using Toplevel() function. I tried to use lambda to try to incorporate the Toplevel() when using the button but the pop out window did not reflect anything. Here is the code I made:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkPDFViewer import tkPDFViewer as pdf
import os
#make tk case
root = Tk()
root.geometry("1000x700+200+100")
root.title("PDF Viewer")
root.configure(bg="light blue")
#view frame
view_frame=Frame(root, bg="light blue", bd=5, width=400)
view_frame.pack(side=LEFT)
#to generate pop up window to view PDFs
def popup(filename):
win=Toplevel()
win.geometry("100x80")
win.title(filename)
v2=None
file = ''
#search for files
def viewpdf():
#make v2 global
global v2
filename=filedialog.askopenfilename(initialdir=os.getcwd(),
title="Select PDF File",
filetype=(("PDF File", ".pdf"),
("PDF File", ".PDF"),
("All File",".txt")))
if filename:
global file
file=filename
#destroy old file if it exists
if v2:
v2.destroy()
#create new pdf images
v1=pdf.ShowPdf()
#clear stored images
v1.img_object_li.clear()
#store new images
v2=v1.pdf_view(view_frame, pdf_location=open(filename,"r"),height=50, width=80)
v2.pack(pady=(0,0))
#set buttons
view_button=Button(view_frame, text='SEARCH FOR FILES', command=lambda: [viewpdf(), popup(file)], width=50, bd=5)
view_button.pack()
root.mainloop()
Update: I have tried adding tkinter.TopLevel() inside the def viewpdf() and it worked! I have deleted the def popup() as well.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkPDFViewer import tkPDFViewer as pdf
import os
#make tk case
root = Tk()
root.geometry("1000x700+200+100")
root.title("PDF Viewer")
root.configure(bg="light blue")
#view frame
view_frame=Frame(root, bg="light blue", bd=5, width=400)
view_frame.pack(side=LEFT)
v2 = None
#search for files
def viewpdf():
#make v2 global
global v2
filename=filedialog.askopenfilename(initialdir=os.getcwd(),
title="Select PDF File",
filetype=(("PDF File", ".pdf"),
("PDF File", ".PDF"),
("All File",".txt")))
if filename:
#destroy old file if it exists
if v2:
v2.destroy()
#create new pdf images
v1=pdf.ShowPdf()
#clear stored images
v1.img_object_li.clear()
#set a new pop out window
newWindow=tkinter.Toplevel(view_frame)
#store new images
v2=v1.pdf_view(newWindow, pdf_location=filename, height=50, width=80)
v2.pack(pady=(0,0))
I am very new to Tkinter and GUI in general, but I tried looking around for similar problems (and found some) and I still can't seem to get it to work. I want to save the stringpath "path_to_ifc_file" after clicking the button, so that I can use it in another script later on.
from tkinter import *
from tkinter import filedialog
def BrowseFiles():
path_to_ifc_file = filedialog.askopenfilename(initialdir="../models/", title="Get Ifc-File:",
filetypes=(("Ifc-Files", "*.ifc*"), ("All files", "*.*")))
if path_to_ifc_file == "":
label_file_explorer.configure(text="Get Ifc-File:")
else:
label_file_explorer.configure(text="Found Ifc-File: \n" + Path(path_to_ifc_file).stem + ".ifc")
return path_to_ifc_file
# WINDOW CONFIGURATION
window = Tk()
window.title('Test')
window.geometry("800x280")
# INITIALIZE WIDGETS
label_file_explorer = Label(window, text="Get Ifc-File:")
button_explore = Button(window, text="Browse", command=BrowseFiles)
# DISPLAY WIDGETS
label_file_explorer.grid(column=1, row=1)
button_explore.grid(column=2, row=1)
window.mainloop()
In my mind I just want something like
path_to_ifc_file=<returned value path_to_ifc_file from function BrowseFiles()>
I appreciate every help I can get! Thanks in advance :)
How do I send send text from the label to entry box, or send directly the path of the image to entry box in tkinter?
from tkinter import *
from PIL import ImageTk,Image
from tkinter import filedialog
root = Tk()
def open():
root.filename = filedialog.askopenfilename(initialdir="/", title="Select A File",filetypes=(("jpg files", "*.jpg"), ("all files", "*.*")))
my_label = Label(root, text=root.filename).pack()
my_btn = Button(root, text="Open files", command=open).pack()
#entry box
txt2 = Entry(root)
txt2.place(x=10, y=45)
root.mainloop()
Did you mean get text in label and insert the text to an Entry?
If yes, you can just make a StringVar() in the Entry
For example like this:
from tkinter import * #For python 3
from Tkinter import * #For python 2
root = Tk()
txt = StringVar()
#For inserting text
txt.set("This is a label and an entry")
label = Label(root, textvariable=txt).pack()
entry = Entry(root, textvariable=txt).pack()
root.mainloop()
I am new to python and I'm trying to save a file that is picked from the file chooser to an image folder.
here is some of the code:
def open_file(self):
root = tk.Tk()
# hides tk main window
root.withdraw()
canvas1 = tk.Canvas(root, width=0, height=0)
canvas1.pack()
self.jpg = filedialog.askopenfilename(initialdir="/", title="Select file",
filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*")))
FrameDesign.selected(self, self.jpg)
root.destroy()
return self.jpg
# path = 'C:/Users/AJONES2/Desktop/img'
# fullpath = os.path.join(path, filename)
img.save('C:/Users/AJONES2/Documents/img', 'JPEG')
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 4 years ago.
What i want to do :
1.To create a File Dialog box with an option to select a file
1.1 First button to select file read its location
->Able to do it with the solution provided from below link
filedialog, tkinter and opening files
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
1.2 Second button to start processing
->By adding another button to start
->Adding a function with argument process_it. ->So function call with argument is not working for my code
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
#new code added by me:
self.button = Button(self, text="Start Now", command=self.process_it(arg_1), width=10)
self.button.grid(row=2, column=0, sticky=W)
def load_file(self):
#new code added by me:
global arg1
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
#new code added by me:
arg_1 = fname
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
# new function added by me:
def process_it(self, arg_1):
#use the arg_1 further, example :
print(arg_1)
if __name__ == "__main__":
MyFrame().mainloop()
You can write factory function to pass some arguments.
def command_factory(arg_1):
def process_it():
print(arg_1)
return process_it
using
Button(self, text="Start Now", command=command_factory(arg_1))
or just
Button(self, text="Start Now", command=lambda: self.proccess_it(arg_1))
But in this case you need to be sure that arg_1 variable is not changing to avoid late binding.