I'm trying the implement the browse functionality in Tkinter, I'm able to implement the browse file option, however, after selecting the file at a particular location it's displaying file location on the console, how to print that location on the label?
At the following place, file_location or file_name should be printed.
entry_1.insert(0, 'File_location')
For e.g. the file location is
Path with file name C:\Users\Desktop\test\test.txt
, so this file location should be printed on the label instead of the console.
And along with that, if I want only a path without a file name then how it can be done?
Path without file name. C:\Users\Desktop\test
What extra functionality do I need to add in order to implement this feature? Any help would be appreciated.
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from io import StringIO
import sys
import os
root = Tk()
root.geometry('700x650')
root.title("Data Form")
def file_opener():
input = filedialog.askopenfiles(initialdir="/")
print(input)
for i in input:
print(i)
label_1 = Label(root, text="Location",width=20,font=("bold", 10))
label_1.place(x=65,y=130)
x= Button(root, text='Browse',command=file_opener,width=6,bg='gray',fg='white')
x.place(x=575,y=130)
entry_1 = Entry(root)
entry_1.place(x=240,y=130,height=20, width=300)
entry_1.insert(0, 'File_location')
root.mainloop()
Instead of using
filedialog.askopenfile(initialdir="/")
use
filedialog.askopenfilename(initialdir="/")
if you want to select multiple files and get a tuple as the input use
filedialog.askopenfilenames(initialdir="/")
And for the path without the file name use this
import os
os.path.dirname(input)
you can Insert the text to the Entry by using this
Updated:
entry_1.delete(0, END)
entry_1.insert(0, input[0])
Full Modified code
(Updated:)
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from io import StringIO
import sys
import os
root = Tk()
root.geometry('700x650')
root.title("Data Form")
def file_opener():
# input = filedialog.askopenfilenames(initialdir="/") # for selecting multiple files
input = filedialog.askopenfilename(initialdir="/")
entry_1.delete(0, END)
entry_1.insert(0, input)
label_1 = Label(root, text="Location", width=20, font=("bold", 10))
label_1.place(x=65, y=130)
x = Button(root, text='Browse', command=file_opener, width=6, bg='gray', fg='white')
x.place(x=575, y=130)
entry_1 = Entry(root)
entry_1.place(x=240, y=130, height=20, width=300)
entry_1.insert(0, 'File_location')
root.mainloop()
Related
This question already has answers here:
How do I get the Entry's value in tkinter?
(2 answers)
Closed 17 days ago.
enter image description here
when i write in the execution's entry i want this to be saved in another text file
how ?
and this is my code
from tkinter import ttk
from tkinter import *
root = Tk()
label1=ttk.Label(root,text="Type your message : ",font="classic")
label1.pack()
entry1=ttk.Entry(root,width=70)
entry1.pack()
button=ttk.Button(root,text="Send",padding=7,cursor="hand2")
button.pack()
def Bclick () :
entry1.delete(0,END)
print("sent")
button.config(command=Bclick)
file = input("yo :")
root.mainloop()
with open('text','w') as myfile :
myfile.write(file)
To get the value from an Entry widget, you need to use its get method, e.g.,
from tkinter import ttk
from tkinter import *
root = Tk()
label1 = ttk.Label(root, text="Type your message : ", font="classic")
label1.pack()
entry1 = ttk.Entry(root, width=70)
entry1.pack()
button = ttk.Button(root, text="Send", padding=7, cursor="hand2")
button.pack()
def Bclick():
entryvalue = entry1.get() # get what's in the Entry widget before clearing it
entry1.delete(0,END)
print("sent")
# write the value to a file
with open("text", "w") as myfile:
myfile.write(entryvalue) # write it to your file
button.config(command=Bclick)
#file = input("yo :") # not sure what this was for, so I've commented it out
root.mainloop()
After this, your file text should contain whatever you entered into the Entry box.
What your current code is doing is building the interface then it collects input through the terminal and writes it to a file, and then finally it displays the window to the user.
What you want to do instead is inside of your buttons callback method, collect the input from the Entry widget, and save whatever it contains in the your buttons callback.
from tkinter import ttk
from tkinter import *
filename = "MyTextFile.txt"
root = Tk()
label1=ttk.Label(root,text="Type your message : ",font="classic")
label1.pack()
entry1=ttk.Entry(root,width=70)
entry1.pack()
button=ttk.Button(root,text="Send",padding=7,cursor="hand2")
button.pack()
def Bclick():
text = entry1.get()
with open(filename, "wt") as fd:
fd.write(text)
entry1.delete(0,END)
print("sent")
button.config(command=Bclick)
root.mainloop()
i want to create a simple GUI form, which asks user to browse file and then display result, i have wrote following code :
import numpy as np
import pandas as pd
from tkinter import *
from tkinter.filedialog import askopenfilename
def read_file():
filename =askopenfilename()
label1.insert(0,filename)
return
def display_file():
filename1 =label1.get()
data =pd.read_csv(filename1)
print(data.head())
root =Tk()
#root.withdraw()
label1 =Entry(root,width=100)
button =Button(root,text="Read csv file",command=read_file)
button1 =Button(root,text="Display file",command=display_file)
button.pack()
label1.pack()
button1.pack()
root.mainloop()
result is following image :
when i click read csv file, it gives me possibility to read file and result is like this :
now i need display part :
def display_file():
filename1 =label1.get()
data =pd.read_csv(filename1)
print(data.head())
this function just display files in working directory, but i need to show(5 rows of dataframe) in GUI form, let us suppose that file contains just two column - please tell me how to do? i have searched a lot but could not find exact solution (different solutions was presented and i was confused)
You have to add a Tkinter element where you want the data to be displayed (here, I choose Label) using a Variable element and set this element to hold your data from inside the display_file formula:
import numpy as np
import pandas as pd
from tkinter import *
from tkinter.filedialog import askopenfilename
def read_file():
filename = askopenfilename()
label1.insert(0, filename)
return
def display_file():
filename1 = label1.get()
data = pd.read_csv(filename1)
print(data.head())
pd_variable.set(data.head())
root = Tk()
# root.withdraw()
label1 = Entry(root, width=100)
button = Button(root, text="Read csv file", command=read_file)
button1 = Button(root, text="Display file", command=display_file)
pd_variable = Variable(root)
label2 = Label(root, textvariable=pd_variable)
button.pack()
label1.pack()
button1.pack()
label2.pack()
root.mainloop()
I'm trying to use the theme "sun valley" for a python-based installer that i'm working on. I have all the .tcl files installed and everything should be working, but its not. I even tried to use the built in styles
here's my code:
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import os
director = os.path.dirname(__file__)
friendlyName = "python"
file = ""
import shutil
global User
try:
User = os.getlogin()
except:
User="home"
from tkinter import *
from tkinter import filedialog
from os import path
path = fr"C:\{User}\AppData\Local\{friendlyName}"
def install():
try:
os.mkdir(path)
except:
pass
shutil.copy(file, path)
#E1 = Entry(top, bd =5)
window = Tk()
# Just simply import the azure.tcl file
style = ttk.Style(window)
dir_path = os.path.dirname(os.path.realpath(__file__))
window.tk.call('source', os.path.join(dir_path, 'theme\dark.tcl'))
print(os.path.join(dir_path, 'theme\dark.tcl'))
#window.tk.call("set_theme", "dark")
style.theme_use('sun-valley-dark')
window.geometry("600x400")
window.rowconfigure(20)
window.columnconfigure(20)
def askdir():
direct = filedialog.askdirectory()
path = direct
textBox.delete(0, END)
textBox.insert(0, path)
#textBox.set(path)
window.update_idletasks()
window.title(f"{friendlyName} install")
chooseText = Label(window, text=f"choose a place for {friendlyName} to be installed")
chooseText.grid(column=2, row=0)
chooseButton = Button(window, text="choose path", command=askdir)
chooseButton.grid(column=1, row=3)
textBox = Entry(window, text=f"{path}")
textBox.insert(0, path)
textBox.grid(column=2, row=3)
chooseButton = Button(window, text="install", command=install)
chooseButton.grid(column=3, row=4)
chooseButton = Button(window, text="quit", command=window.destroy)
chooseButton.grid(column=1, row=4)
window.mainloop()
heres what outputs:
Need to use ttk widgets
instead of chooseText = Label(window, text=f"choose a place for {friendlyName} to be installed")
it would be chooseText = ttk.Label(window, text=f"choose a place for {friendlyName} to be installed")
then the style will show up!
I am trying to create a tkinter gui that performs a certain calculation. I create a window to ask for input to do the calculations. However, each time I run my code 2 windows pop up instead of one. Is there a way to automatically close the blank window when I run my code such that the user would only see the window that asks for input.
For simplicity I changed all buttons to close the applications.
import numpy as np
import pandas as pd
from datetime import datetime
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox
import blpapi
import pdblp
con = pdblp.BCon(timeout=5000)
con.start()
s= ttk.Style()
s.theme_use('xpnative')
root =tk.Tk()
root.title("Vega Requirement Application")
root.geometry("600x400")
ticker_var= tk.StringVar()
volume_var= tk.StringVar()
def close():
root.destroy()
def clear_all():
root.destroy()
def vega_calculation():
root.destroy()
ticker_label = ttk.Label(root, text='Bloomberg Ticker:',font=('calibre',10,'normal'))
ticker_entry = ttk.Entry(root, textvariable = ticker_var,font=('calibre',10,'normal'))
volume_label = ttk.Label(root, text='Volume:',font=('calibre',10,'normal'))
volume_entry = ttk.Entry(root, textvariable = volume_var,font=('calibre',10,'normal'))
run_btn = ttk.Button(root, text = 'Calculate', command = vega_calculation, width = 13)
close_btn = ttk.Button(root, text= 'Close App', command = close, width =13)
clear_btn = ttk.Button(root, text= 'Clear table', command = clear_all, width=13)
ticker_label.grid(row=0,column=0)
ticker_entry.grid(row=0,column=1)
volume_label.grid(row=1,column=0)
volume_entry.grid(row=1,column=1)
run_btn.grid(row=0,column=2)
close_btn.grid(row=1, column=2)
clear_btn.grid(row=0, column =4)
root.mainloop()
The following two lines will create an instance of Tk() because there is no instance of Tk() when they are executed:
s = ttk.Style() # create an instance of Tk() if there is none
s.theme_use('xpnative')
Move the two lines to after root = tk.Tk() so that it uses the already created instance of Tk():
root = tk.Tk()
s = ttk.Style() # use existing instance of Tk(), root
s.theme_use('xpnative')
I am relatively new to programming and I noticed that coding everything in 2 files (settings and main) gets very messy as your code grows.
However, when I split my code into many files, I run into issues where I cannot import fileB.py intro FileA.py and use variables or widgets from file A inside my file B (I get undefined names error).
I am using tkinter for the UI, so my main file is the tk loop (main.py). Each button refers to functions in different files. It works well, until my function includes button states or entry text.
This example is with tkinter but I run into this problem on many occasions, because of my code structure I believe.
File A (main.py)
import FileB
import tkinter
from tkinter import Checkbutton, Tk, Entry, BooleanVar
root = Tk() # initialize blank window
root.geometry("500x500")
# text entry
E1 = Entry(root, bd=5, width = 8)
E1.grid(row=0, column=1)
# Checkbox
CB_var = BooleanVar()
CB = Checkbutton(root, text="Get text", variable=CB_var, command=FileB.get_text() )
CB.grid(row=0, column=2)
root.mainloop()
FileB (FileB.py)
def get_text():
if CB.var == True:
entry_text = E1.get()
E1.config(state=DISABLED)
print(entry_text)
E1.delete(0, END)
elif CB.var == False:
E1.config(state=NORMAL)
print("Checkbox not selected")
Since E1 is defined before my function is called, I would expect my function to be able to change the state of E1, get its text and empty the text; as if the function was in my main.py.
The actual output is undefined name error since E1 is not a variable in my FileB.
As FileB is imported by main.py, FileB cannot access objects in main.py. You need to pass the objects in main.py via function parameters.
Suggest to put your widgets into a class and pass the instance of the class to FileB.get_text() function.
File A (main.py)
from tkinter import Checkbutton, Tk, Entry, BooleanVar
import FileB
class GUI:
def __init__(self, root=None):
# text entry
self.E1 = Entry(root, bd=5, width = 8)
self.E1.grid(row=0, column=1)
# Checkbox
self.CB_var = BooleanVar()
self.CB = Checkbutton(root, text="Get text", variable=self.CB_var, command=lambda: FileB.get_text(self))
self.CB.grid(row=0, column=2)
root = Tk() # initialize blank window
root.geometry("500x500")
GUI(root)
root.mainloop()
File B (FileB.py)
from tkinter import DISABLED, NORMAL, END
def get_text(gui):
if gui.CB_var.get() == True:
entry_text = gui.E1.get()
gui.E1.config(state=DISABLED)
print(entry_text)
gui.E1.delete(0, END)
else:
gui.E1.config(state=NORMAL)
print("Checkbox not selected")