I am making a gui interface to make my script available to general user. My question is - I have a entry widget which takes 'file path' as value when user picks a file using browse button. Problem is entry widget shows the beginning (left end) of file path but I would prefer to see the right end of the file path.
And here is my script.
from Tkinter import *
from tkFileDialog import askopenfilename
app = Tk()
app.title("ABC")
app.geometry("300x100")
def browse_for_file(entry_name, filetype):
File_path = askopenfilename(filetypes = filetype)
entry_name.delete(0, END)
entry_name.insert(0, File_path)
templ_filename = StringVar()
templ_entry = Entry(app, textvariable = templ_filename, width = 30)
templ_entry.grid(row = 3, column = 1, sticky=W)
filetype_fasta = [('fasta files', '*.fasta'), ('All files', '*.*')]
button_templ = Button(app, text = 'Browse', width =6, command = lambda:browse_for_file(templ_entry, filetype_fasta))
button_templ.grid(row = 3, column = 2)
app.mainloop()
Use
entry.xview_moveto(1)
xview_moveto() takes fractions, where 0 defines the left and 1 the right part.
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()
For example I want to get an input from tkinter and in the GUI it says "how much do you like cars from 1 - 10?" and then the victim inputs a number for example 8 how would I transfer my input to my settings.ini?
My Code:
root = Tk()
config = ConfigParser()
updater = ConfigUpdater()
path = os.path.dirname(os.path.abspath(__file__))
configPath = os.path.join(path, "settings.ini")
updater.read('settings.ini')
updater['Trading Settings']['maximum_value_gain'].value = "the input I want from tkinter user"
updater.update_file()
root.mainloop()
For your case, you can use OptionMenu for the rating input as below:
import os
import tkinter as tk
from configupdater import ConfigUpdater
appPath = os.path.dirname(os.path.abspath(__file__))
configPath = os.path.join(appPath, "settings.ini")
updater = ConfigUpdater()
updater.read(configPath) # settings.ini must exists, otherwise exception
root = tk.Tk()
tk.Label(root, text='How much do you like cars (from 1 - 10)?').grid(row=0, column=0)
rating = tk.StringVar()
rating_opt = tk.OptionMenu(root, rating, *range(1, 11)) # dropdown with values 1 to 10
rating_opt.config(width=5)
rating_opt.grid(row=0, column=1)
def update():
value = rating.get()
# update ini file only when user has selected a rating
if value:
updater['Trading Settings']['maximum_value_gain'].value = rating.get()
updater.update_file()
tk.Button(root, text='Update', command=update).grid(row=2, column=0, columnspan=2)
root.mainloop()
I've recently finished a data standardisation script and am currently trying to make it more user-friendly by creating an app with Tkinter. I have already managed to run the data standardisation script through Tkinter, but the script requires minor changes between different data sets.
What I'm trying to achieve is inserting a user-defined piece of text to a specific location in the script. I have tried the text widget on Tkinter, however I have only managed to open the script in the app, which is something I avoid doing (optimally the app user would not even need to see the original code).
What I'm rather trying to do is having a Tkinter textbox, with a 'Run' button next to it. That way when a user inserts a specific name (e.g. 'Law Conference Attendees Jan 2020') it would automatically place this piece of text here df['Data Identifier'] = ''
My current Tkinter code looks like this:
def __init__(self):
super(Root, self).__init__()
self.title("Python Tkinter Dialog Widget")
self.minsize(320, 200)
self.text_area = Text()
self.text_area.grid(column = 2, row = 3)
self.labelFrame = ttk.LabelFrame(self, text = "Open File")
self.labelFrame.grid(column = 0, row = 1, padx = 20, pady = 20)
self.button()
self.button1()
self.button2()
self.textbox()
self.textbox1()
self.textbox2()
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Browse a File",command = self.open_file)
self.button.grid(column = 1, row = 1)
def button1(self):
self.button1 = ttk.Button(self.labelFrame, text = "Cleanse Campaign Codes",command = self.standardize)
self.button1.grid(column = 1, row = 7)
def button2(self):
self.button2 = ttk.Button(self.labelFrame, text = "Cleanse Data",command = self.helloCallBack)
self.button2.grid(column = 1, row = 8)
def textbox(self):
self.textbox = ttk.Entry(self.labelFrame)
self.textbox.grid(column = 6, row = 1)
def textbox1(self):
self.textbox1 = ttk.Entry(self.labelFrame)
self.textbox1.grid(column = 6, row = 2)
def textbox2(self):
self.textbox2 = ttk.Entry(self.labelFrame)
self.textbox2.grid(column = 6, row = 3)
def helloCallBack(self):
os.system('python data_cleansing_final.py')
def open_file(self):
open_return = filedialog.askopenfile(initialdir = "C:/", title="Select file to open", filetypes=(("python files", "*.py"), ("all files", "*.*")))
for line in open_return:
self.text_area.insert(END, line)
def standardize(self):
open_return = open_return.apply(lambda x: difflib.get_close_matches(x, textbox)[0])
root = Root()
root.mainloop()
I would very much appreciate any help or advice.
You could add a StringVar to your textbox.
self.inputstring = ttk.StringVar(self.lableFrame, value = 'value')
self.textbox2 = ttk.Entry(self.labelFrame, textvariable = self.inputstring)
self.textbox2.grid(column = 6, row = 3)
To read the variable you should use:
self.inputstring.get()
You can make an entry:
text = Entry(root, width=10)
text.grid(column=0, row=0)
With a button next to it:
run = Button(root, text="Run", width=10, command=runClicked)
run.grid(column=1, row=0)
And then a method called runClicked above these:
def runClicked():
userText = text.get()
And then the variable userText variable will hold whatever the user types in and you can use it as you wish.
All in all your code would look something like:
def runClicked():
userText = text.get()
text = Entry(root, width=10)
text.grid(column=0, row=0)
run = Button(root, text="Run", width=10, command=runClicked)
run.grid(column=1, row=0)
I am experiencing some issues when displaying the location of the image selected. Is there a reason why it displays <_io.TextIOWrapper name =along with mode='r'encoding ='cp1252>? I just want it to display the location of the image along with the name of the image not those extra stuff. Is there something that I am doing that is causing this to occur? Please advise.
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Upload Image", command = self.fileDialog)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfile(initialdir = "/", title = "Select a File", filetype = (("jpeg", "*.jpg"), ("All files", "*.")))
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)
filedialog.askopenfile gives file object, not file name.
You have to display self.filename.name instead of self.filename
Full working example
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
file_object = filedialog.askopenfile(title="Select file")
print('file_object:', file_object)
print('file_object.name:', file_object.name)
#data = file_object.read()
label = tk.Label(root, text=file_object.name)
label.pack()
root.mainloop()
Or use askopenfilename instead of askopenfile and you get file name.
Full working example
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
filename = filedialog.askopenfilename(title="Select file")
print('filename:', filename)
#data = open(filename).read()
label = tk.Label(root, text=filename)
label.pack()
root.mainloop()
I would like to create a function or class that has the proper formatting to create a text label, entry field, and button. The button would allow me to browse through my directory and populate the entry field with the chosen directory. The code I have allows me to do most of this, however the directory is always populated in the last entry field instead of the one the button refers to.
I am new to tkinter and GUIs so apologies if this is a simple solution, I assume the problem is with root.name.set referring to the function that was called last.
from tkinter import *
from tkinter import filedialog
def askdirectory():
dirname = filedialog.askdirectory()
root.name.set(dirname)
def dirField(root, label, rowNum):
text = StringVar()
text.set(label)
dirText = Label(root, textvariable = text, height =4)
dirText.grid(row = rowNum, column = 1)
dirBut = Button(root, text = 'Browse', command = askdirectory)
dirBut.grid(row = rowNum, column = 3)
root.name = StringVar()
adDir = Entry(root,textvariable = root.name, width = 100)
adDir.grid(row = rowNum, column = 2)
if __name__ == '__main__':
root = Tk()
root.geometry('1000x750')
adText = "Select directory of Ads"
userText = "Select directory of User credentials"
adField = dirField(root, adText, 1)
userField = dirField(root, userText, 2)
root.mainloop()
You should realise that you need to have each Entry have its own textvariable. Otherwise they will overlap. Have a look at my code, which should get you going.
from tkinter import *
from tkinter import filedialog
path = [None, None] # Fill it with the required number of filedialogs
def askdirectory(i):
dirname = filedialog.askdirectory()
path[i].set(dirname)
def dirField(root, label, rowNum, i):
dirText = Label(root, text=label)
dirText.grid(row=rowNum, column=0)
dirBut = Button(root, text='Browse', command=lambda: askdirectory(i))
dirBut.grid(row=rowNum, column=2)
path[i] = StringVar()
adDir = Entry(root, textvariable=path[i], width=50)
adDir.grid(row=rowNum, column=1)
if __name__ == '__main__':
root = Tk()
adText = "Select directory of Ads"
userText = "Select directory of User credentials"
adField = dirField(root, adText, 0, 0)
userField = dirField(root, userText, 1, 1)
root.mainloop()