I'm just starting to use tkinter and it is a little difficult to handle it. Check this sample :
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import Tkinter as tk
import tkFileDialog
def openfile():
filename = tkFileDialog.askopenfilename(title="Open file")
return filename
window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()
window.mainloop()
I juste created a browse button which keep the file path in the variable "filename" in the function openfile(). How can i put the content of "filename" in a variable out of the function ?
For example I want to put it in the variable P and print it in a terminal
def openfile():
filename = tkFileDialog.askopenfilename(title="Open file")
return filename
window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()
window.mainloop()
P = "the file path in filename"
print P
I also also want to put the file path in a widget Entry(), and as same as below, get the text in the Entry widget in another global variable.
If someone knows, it would be nice.
There are at least two different ways of doing it:
1) Bundle your whole app in a class like this:
import Tkinter as tk
import tkFileDialog
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self) # create window
self.filename = "" # variable to store filename
tk.Button(self, text='Browse', command=self.openfile).pack()
tk.Button(self, text='Print filename', command=self.printfile).pack()
self.spinbox = tk.Spinbox(self, from_=0, to=10)
self.spinbox.pack(pady=10)
tk.Button(self, text='Print spinbox value', command=self.printspinbox).pack()
self.mainloop()
def printspinbox(self):
print(self.spinbox.get())
def openfile(self):
self.filename = tkFileDialog.askopenfilename(title="Open file")
def printfile(self):
print(self.filename)
if __name__ == '__main__':
App()
In this case, filename is an attribute of the App, so it is accessible from any function inside the class.
2) Use a global variable:
import Tkinter as tk
import tkFileDialog
def openfile():
global filename
filename = tkFileDialog.askopenfilename(title="Open file")
def printfile():
print(filename)
def printspinbox():
print(spinbox.get())
window = tk.Tk()
filename = "" # global variable
tk.Button(window, text='Browse', command=openfile).pack()
tk.Button(window, text='Print filename', command=printfile).pack()
spinbox = tk.Spinbox(window, from_=0, to=10)
spinbox.pack(pady=10)
tk.Button(window, text='Print spinbox value', command=printspinbox).pack()
window.mainloop()
Related
I'm new to Tkinter and I'm trying to create a simple Button that opens a file dialog box, where the user chooses which CSV file to open. Under the button there is a label that should display the file path for the file that was opened.
When I click on the button once, everything works as expected. However, if I click on it a second time and select a different file, the new filepath overlaps with the previous one, instead of replacing it.
Here is the code for the implementation function (please let me know if you need more bits of code for context):
def open_csv_file():
global df
global filename
global initialdir
initialdir = r"C:\Users\stefa\Documents\final project models\Case A"
filename = filedialog.askopenfilename(initialdir=initialdir,
title='Select a file', filetypes = (("CSV files","*.csv"),("All files","*.*")))
df = pd.read_csv(os.path.join(initialdir,filename))
lbl_ok = tk.Label(tab2, text = ' ') #tab2 is a ttk.Notebook tab
lbl_ok.config(text='Opened file: ' + filename)
lbl_ok.grid(row=0,column=1)
Here is how to do it with .config(), create the label instance just once (can then grid as much as you want but probably just do that once too), then just configure the text:
from tkinter import Tk, Button, Label, filedialog
def open_file():
filename = filedialog.askopenfilename()
lbl.config(text=f'Opened file: {filename}')
root = Tk()
Button(root, text='Open File', command=open_file).grid()
lbl = Label(root)
lbl.grid()
root.mainloop()
You can use a StringVar for this. Here is an example that may help you:
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.geometry('200x200')
def openCsv():
csvPath.set(askopenfilename())
csvPath = StringVar()
entry = Entry(root, text=csvPath)
entry.grid(column=0, row=0)
btnOpen = Button(root, text='Browse Folder', command=openCsv)
btnOpen.grid(column=1, row=0)
root.mainloop()
Here is my code. It works how I want it to but I have always been told it is poor coding practice to use global variables and that they can cause problems, although I cannot figure out how to get the labels to change without using them. Any help is appreciated.
import tkinter as tk
from tkinter import filedialog, Text
import os
status = 'Start'
startStopBG = 'light green'
def main():
root = configure_screen()
root.mainloop()
def configure_screen():
root = tk.Tk()
root.title('APP')
root.config(bg='snow3')
root.minsize(700, 700)
browse_button = tk.Button(root, text='Browse', width='10', command=browse)
browse_button.place(x=605, y=10)
global text
text = tk.Text(root, height=1.3, width=73)
text.insert(tk.END, 'Enter Path to Storage HERE')
text.place(x=10, y=13)
global start_stop
start_stop = tk.Button(root, height=1, width=12, text=status, bg=startStopBG,
font=('Helvetica', '40'), command=start_scanning)
start_stop.pack(pady=50)
return root
def browse():
path = filedialog.askdirectory(initialdir='/', title='Select where you want to save your file')
text.delete('1.0', tk.END)
text.insert(tk.END, path)
def start_scanning():
global status
global startStopBG
global start_stop
if status == 'Start':
status = 'Stop'
startStopBG = 'red'
else:
status = 'Start'
startStopBG = 'light green'
start_stop.config(text=status, bg=startStopBG)
if __name__ == '__main__':
main()
First of all you can use a class to your main window and instead of global variables you use class variables. Second I would recommend you to use tkinter variables to store important data from widget since the path and the status. For example, if you use text=tk.StringVar() you can set or get the value from text with text.set('value') or text.get(). Tkinter variables are object and if you define an object in your main you can access it as a global variable inside functions without the need of using global. However, in your code, to use text as a StringVar you should change the Text widget for an Entry widget, which is more appropriated since path is a single entry value and not a text. The same way you can change your start_stop button to a Checkutton and it will make the color change unnecessary since you can define colors for background and selectcolor.
The code bellow includes all changes I suggest here:
import tkinter as tk
from tkinter import filedialog, Text
import os
class Main(tk.Tk):
def __init__(self):
super(Main, self).__init__()
self.title('APP')
self.config(bg='snow3')
self.minsize(700, 700)
self.status = tk.IntVar()
self.text = tk.StringVar(self, value='Enter Path to Storage HERE')
browse_button = tk.Button(self, text='Browse', width='10',
command=self.browse)
browse_button.place(x=605, y=10)
tk.Entry(self, width=73, textvariable=self.text).place(x=10, y=13)
self.start_stop = tk.Checkbutton(self, height=1, width=12, text="start",
font=('Helvetica', '40'), indicator=False,
bg='light green', selectcolor='red',
variable=self.status, command=self.start_scanning)
self.start_stop.pack(pady=50)
def browse(self):
path = filedialog.askdirectory(initialdir='/', title='Select where you want to save your file')
self.text.set(path)
def start_scanning(self):
if self.status.get():
self.start_stop.config(text='stop')
else:
self.start_stop.config(text='start')
if __name__ == '__main__':
Main().mainloop()
As I understood you want to change label
Try This:
import tkinter as tk
def main():
def change_label_text():
mylabel.config(text="yeee My Text has Been changed")
def change_button_text():
mybutton.config(text="yee Button text has been changed")
root = tk.Tk()
root.title('Change Label')
root.config(bg='snow3')
root.geometry('400x300')
mybutton = tk.Button(root, text='Press Me To Change Button Text', command=change_button_text)
mybutton.pack(side='top')
mylabel = tk.Label(root, text='Press The Button Above To Change My text')
mylabel.pack(side='bottom')
mybutton2 = tk.Button(root, text="Press me", command=change_label_text)
mybutton2.pack(side='bottom')
root.mainloop()
main()
By making functions inside the mainloop you dont need to do global stuff and all
I am new to trying this TKinter . I have to browse files and folders. What i need is to get the pathname of the files and folders i have browsed. i Am not not able to understand where to put my piece of code in this script? . How can i do it? or should i write a seperate . Am stuck in here. I browsed through stack overflow many have problem of getting filenames returned back to their program s with no proper solution. Can anyone help me on this?Advance thanks.
from Tkinter import Tk, RIGHT, BOTH, RAISED,Label
from ttk import Frame, Button, Style
from PIL import Image, ImageTk
import tkFileDialog
import tkMessageBox
import glob
#global root
f1=""
f2=""
def FileBrowser():
img1_path = tkFileDialog.askopenfilename(parent=root,title='Provide the Query Image ')
global f1
f1=img1_path
#print img1_path
def PathBrowser():
img2_path =tkFileDialog.askdirectory(parent=root,title='Provide the path for Training Dataset ')
global f2
f2=img2_path
#print img2_path
def matcher():
imlist=glob.glob(f2)
print imlist
for file in imlist:
print file
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
global root
self.parent.title("Medical CBIR")
self.style = Style()
self.style.theme_use("default")
frame = Frame(self, relief=RAISED, borderwidth=1)
w = Label(self, text="QUERY IMAGE")
w.pack()
style = Style()
style.configure("TFrame", background="#333")
im = Image.open('D:/database/Mixture/1.png')
img = ImageTk.PhotoImage(im)
label1 = Label(self, image=img)
label1.image = img
label1.place(x=155, y=70)
frame.pack(fill=BOTH, expand=1)
self.pack(fill=BOTH, expand=1)
Retrieve_Image=Button(self,text="Retrieve Related Images",command=matcher)
Retrieve_Image.pack(side=RIGHT, padx=5, pady=5)
Training_Image = Button(self, text="Path of Training Images",command=PathBrowser)
Training_Image.pack(side=RIGHT, padx=5, pady=5)
Test_image = Button(self,text="Browse Test_Image",command=FileBrowser)
Test_image.pack(side=RIGHT, padx=5, pady=5)
def main():
global root
root = Tk()
#root.geometry("300x200+300+300")
root.geometry("500x500")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
# Comparison.py(2nd file)
import cv2
import sys
import GUItkinter
img1_path =GUITKinter.FileBrowser()
img2_path =GUITKinter.PathBrowser()
imlist=glob.glob(f2)
for file in imlist:
compare(img1_path,file) #Function to compare images for similarity
#display the retrieved results
Error: Bad window pathname in img1_path =GUITKinter.FileBrowser()
You have to work out the code yourself. But what I'll do is provide you a way how to format your code & how to implement the problem you are having.
import tkFileDialog
from Tkinter import Tk,Button,StringVar,Entry
class MainClass():
def __init__(self,master):
self.parent=master
self.mainfunc()
def mainfunc(self):
self.path_setup = StringVar()
browse=Button(root,text="Browse",command=lambda:self.path_setup.set(tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])))
browse.grid(row=1,column=1,sticky='E')
path_entry = Entry(root, textvariable=self.path_setup,state='disabled')
path_entry.grid(row=1,column=0,sticky='E')
if __name__ == '__main__':
root = Tk()
root.title("My Program")
root.wm_resizable(0,0)
client = MainClass(root)
root.mainloop()
It's a "piece" of code which I was working on. I have formatted it for you.
Hope this gets you going :)
This is my main file:
ExcelAppl = win32com.client.Dispatch('Excel.Application')
Workbook = ExcelAppl.Workbooks.Open('excel file path')
Sheet = Workbook.Worksheets.Item(1)
This is the Python GUI:
root = Tk()
def callback():
file_path = tkFileDialog.askopenfilename(filetypes=[("Excel files","*.xls")])
print "the file path %s",file_path
Text_button.insert(INSERT,file_path)
def execute():
execfile("MainLibrary.py")
Browse_button = Button(text='Browse', command=callback).pack(side=LEFT, padx=10, pady=20, ipadx=20, ipady=10)
Execution_button = Button(text='Convert', command=execute).pack(side=BOTTOM, padx=10, pady=20, ipadx=20, ipady=10)
root.mainloop()
This is my query. I need to get the file_path from the GUI and assign it to Workbook = ExcelAppl.Workbooks.Open('excel file path'). I need to get the path from the GUI and assign the path to my main code. Can anyone help?
You don't need execfile() here.
You could define a function in main_library.py instead:
import win32com.client
def do_something_with_excel_file(filename):
app = win32com.client.Dispatch('Excel.Application')
workbook = app.Workbooks.Open(filename)
worksheet = workbook.Worksheets.Item(1)
# use `worksheet` ...
if __name__=="__main__":
import sys
# get filename from command-line if called as a script
do_something_with_excel_file(sys.argv[1])
Then you could import it in your GUI code:
import tkFileDialog
from Tkinter import as tk
import main_library
def browse():
path = tkFileDialog.askopenfilename(filetypes=[("Excel files","*.xls")])
file_path.set(path)
print "the file path %s", path
def convert():
root.destroy() # quit gui
main_library.do_something_with_excel_file(file_path.get())
root = tk.Tk()
file_path = tk.StringVar()
tk.Label(root, textvariable=file_path).pack()
tk.Button(text='Browse', command=browse).pack()
tk.Button(text='Convert', command=convert).pack()
root.mainloop()
I'm having trouble returning a variable from a tkinter Button command. Here is my code:
class trip_calculator:
def __init__(self):
file = self.gui()
def gui(self):
returned_values = {}
def open_file_dialog():
returned_values['filename'] = askopenfilename()
root = Tk()
Button(root, text='Browse', command= open_file_dialog).pack()
filepath = returned_values.get('filename')
root.mainloop()
return filepath
root.quit()
I just want to return the filepath of a text file. The tkinter window is open and I can browse and choose the file but it then doesn't return the path.
The way your code is now, filepath is assigned its value before your window even appears to the user. So there's no way the dictionary could contain the filename that the user eventually selects. The easiest fix is to put filepath = returned_values.get('filename') after mainloop, so it won't be assigned until mainloop ends when the user closes the window.
from Tkinter import *
from tkFileDialog import *
class trip_calculator:
def gui(self):
returned_values = {}
def open_file_dialog():
returned_values['filename'] = askopenfilename()
root = Tk()
Button(root, text='Browse', command= open_file_dialog).pack()
root.mainloop()
filepath = returned_values.get('filename')
return filepath
root.quit()
print(trip_calculator().gui())