inserting path in the entry box in Python GUI - python
I'm new to GUI programming. I made a small GUI where the user browses the file and then do the functionalities he wants with the file.
Now i have an Entry Box in the GUI and whenever a user browses for the required file and after he finishes browsing the path to the file should appear in the entry box.
basically i want it like this
befor browsing
after browsing
How can i do this?
My code to the GUI is :
#!/usr/bin/python
import Tkinter as tk
from tkFileDialog import *
import os
class StageGui:
prot=0
log=0
cwd=os.getcwd()
def __init__(self,parent,tex):
self.tex=tex
self.fm=tk.Frame(remodelmain)
self.l1=tk.Label(self.fm, text='Import .prot File').grid(row=0,column=0,sticky='w',padx=5,pady=10)
self.l2=tk.Label(self.fm, text='Import .log File').grid(row=1,column=0,sticky='w',padx=5,pady=10)
self.protentry = tk.Entry(self.fm, width = 50).grid(row=0,column=1,sticky='w',padx=5,pady=10)
self.logentry = tk.Entry(self.fm, width = 50).grid(row=1,column=1,sticky='w',padx=5,pady=10)
self.b1=tk.Button(self.fm, text='Browse',height=1,width=20,command=self.callback).grid(row=0,column=2,sticky='e',padx=5,pady=10)
self.b2=tk.Button(self.fm, text='Browse',height=1,width=20,command=self.callback1).grid(row=1,column=2,sticky='e',padx=5,pady=10)
self.fm.pack()
self.fm0=tk.Frame(remodelmain,width=500,height=500)
self.b3=tk.Button(self.fm0, text='Check',height=1,width=15,command=self.check).grid(row=4,column=2,sticky='e',padx=5,pady=10)
self.b4=tk.Button(self.fm0, text='Inertia',height=1,width=15).grid(row=5,column=2,sticky='e',padx=5,pady=10)
self.b5=tk.Button(self.fm0, text='Summary',height=1,width=15).grid(row=6,column=2,sticky='e',padx=5,pady=10)
self.b6=tk.Button(self.fm0, text='Report',height=1,width=15).grid(row=7,column=2,sticky='e',padx=5,pady=10)
self.fm0.pack(side='right')
self.fm1=tk.Frame(remodelmain,width=200,height=200)
self.tex1= tk.Text(self.fm1,width=130,height=10)
self.l3=tk.Label(self.fm1, text='Status Box:').grid(row=6,column=0,sticky='nw')
self.tex1.grid(row=6,column=1,sticky='s',padx=20,pady=10)
self.fm1.pack(side='left',anchor='w')
def callback(self):
name= askopenfilename()
StageGui.prot=name
self.printstatements(StageGui.prot)
def printstatements(self,name):
self.tex1.insert('end','\nthe file has been imported \n')
s='the path of the imported file is {}\n'.format(name)
self.tex1.insert('end',s)
self.tex1.see(tk.END)
return
def callback1(self):
name1= askopenfilename()
StageGui.log=name1
self.printstatements(StageGui.log)
def check(self):
file=open(StageGui.prot,'r')
a,b,c='|Checks|','|Status|','|Remarks|'
mess='\n{0:10s} \t {1:10s} \t {2:100s}\n'.format(a,b,c)
self.tex.insert('end',mess)
count_string_occurance(file)
remodelmain = tk.Tk()
fmn1=tk.Frame(remodelmain,width=300,height=300)
l3=tk.Label(fmn1, text='Message Box:').grid(row=6,column=0,sticky='nw')
tex= tk.Text(fmn1,width=130,height=60)
tex.grid(row=6,column=1,sticky='s',padx=20,pady=20)
fmn1.pack(side='bottom',anchor='w')
stagegui=StageGui(remodelmain,tex)
remodelmain.title('prototype_remodel')
remodelmain.geometry('1200x1200+300+300')
remodelmain.mainloop()
Create a string varible that is associated with the Entry widget:
self.pathVar = tk.StringVar(self.fm)
self.protentry = tk.Entry(self.fm, width = 50, textvariable=self.pathVar).grid(row=0,column=1,sticky='w',padx=5,pady=10)
Then after getting the path, set the variable to that path:
name= askopenfilename()
self.pathVar.set(name)
Related
How to give option to user for input a value in an exe file ?? I have converted py to exe but i want system number to be dynamic in exe installer
Python Code to generate QR Code in GUI from tkinter import * import datetime import qrcode def img_taker(): cs = Tk() cs.title('qr_code') img = PhotoImage(file='imgdt2.png') Label( cs, image=img ).pack() cs.mainloop() def i_saver(): # Importing library today = datetime.datetime.now() date_time = today.strftime("%d/%m/%Y, %H:%M:%S") # print("date and time:",date_time) # Data to encode data = (f"System_no = 1 \n Date and Time:{date_time}") # Creating an instance of QRCode class qr = qrcode.QRCode(version = 1, box_size = 10, border = 5) # Adding data to the instance 'qr' qr.add_data(data) qr.make(fit = True) img = qr.make_image(fill_color = 'black', back_color = 'white') img.save('imgdt2.png') i_saver() img_taker() Above code is generating qrcode in GUI window that is correct but I want to convert py to exe that I have already done but ,I want the system name to be dynamic as an option during the setting up of an application(exe file configuration) Here I want a dynamic system number configuration as system number is different for the different device:
Tkinter opening multiple files using one code
So I have designed a program that allows you to open 3 CSV files, and translate them into json, and 'clean' them then merge them into one file. The way i have designed it, is that on display, there are 3 buttons for loading each file, but i am wondering if there is a better design that shows only 1 button, which the user can load multiple files that are assigned to different variables, depending on the column headings in these csv files. The problem that I had, is when you load one file, it overrides the previously loaded file. For reference, the csv files can be only 1/3 different formats so the column headings are known. As you can see from a short part of my code, that i have created 2 different loadfile buttons, for the 2 separate files, but is there a way i can have just 1 button, that assisgns different files to different variables? import tkinter as tk from tkinter import * from tkinter import filedialog from tkinter import messagebox import pandas as pd import json import csv import sys import sqlite3 # def loadInspection(): global inspectionFile global label_inspectionFile loadingCSV = filedialog.askopenfilename() inspectionFile = pd.read_csv(loadingCSV) #Making buttons for load and translate and clean loadButton = Button(window1, text="Load Inspections File", command=loadInspection) loadButton.grid(row=0, column=1) #loading first file called inspections def inspectionClean(): global inspectionFile inspectionFile = inspectionFile #Check and remove any duplicates in the Inspection Data inspectionFile = inspectionFile[inspectionFile.duplicated() == False] cleanInsButton = Button(window1, text="Clean", command=inspectionClean) cleanInsButton.grid(row=0, column=3) #loading second file called inventroy def loadInventroy(): global inventroyFile loadingCSV = filedialog.askopenfilename() inventroyFile = pd.read_csv(loadingCSV) #Making buttons for load and translate and clean loadButton = Button(window1, text="Load Inventroy File", command=loadInventroy) loadButton.grid(row=3, column=1) def inventroyClean(): global inventroyFile inventroyFile = inventroyFile #Check and remove any duplicates in the Inspection Data inventroyFile = inventroyFile[inventroyFile.duplicated() == False] cleanInvButton = Button(window1, text="Clean", command=inventroyClean) cleanInvButton.grid(row=3, column=3)
My guess would be this may be a problem with global variables. In general I would recommend using instance/class variables instead, using global variables is generally not advised. Your load functionality could instead be structured like this: class MyCSVLoader: def __init__(self): self.inventory = None self.inspection = None def loadCSV(self): loadingCSV = filedialog.askopenfilename() return pd.read_csv(loadingCSV) def loadAll(self): self.inspection = self.loadCSV() self.inventory = self.loadCSV() However, let me know if this works as I don't have csv files on hand to test it with. Then, you could implement it with one button like this: csvLoader = MyCSVLoader() loadButton = tk.Button(window1, text="Load All Files", command=csvLoader.loadAll) loadButton.grid(row=0, column=1) Which should pop up 1 window after the other for you to select 2 files. The files selected can then be accessed through csvLoader.inventory and csvLoader.inspection. Note that your clean function would also have to go into this class to function properly.
Global variable are not working in this Python code
I have a student that is working on a task and trying to use global variables within a couple functions across different files. I have had to include excerpts of the files. The first file is the main one and when you click the results button in that program (from the main window it creates) it should call the other file and pass a variable. But, he gets the following error... Results.py", line 44, in GiveResults if row[0] == sname: NameError: name 'sname' is not defined I'm hoping that someone with much better ability and knowledge might be able to point us in the right direction to remedy this. If there is a better way to share the code on here then please also let me know. Thanks, Scott 'Solution.py' #This imports the tkinter module of python from tkinter import * #This imports the other windows for use later import Results, New_User, Edit_User #This part forms the main window and controls things such as size, colour, and message main = Tk() main.title('Hello there') main.geometry("1000x600") main['background']='light blue' #This creates a frame for use later window = Frame(main).pack() #Defines a function that when called will convert whatever is in the textboxes to variables def retrieve(): global sname sname = selectedname.get() global sboss sboss = selectedname.get() 'Results.py' from tkinter import * #This is defining the function that the first window is calling upon def GiveResults(): #This is defining the variables as globe for use across windows (Although it isnt working) global sname global sboss global inputt #Defines a quit function to close the window when called def quit(): ResultsGiven.destroy() #This is making the window ResultsGiven = Tk() ResultsGiven.title('You did the program') ResultsGiven.geometry("600x400") ResultsGiven['background']='light blue' #Creating a frame windowr = Frame(ResultsGiven, bg = 'light blue') #Creating a title titlefont = ('papyrus', 30) title = Label(windowr, text='Results', font=titlefont) title.config(height=1, width=400) title.pack(side=TOP, fill = 'x') #Creating a canvas canvasr = Canvas(windowr, width = 400, height = 400, background = 'light blue') canvasr.pack() #This is importing the csv module of python import csv #This is opening the csv file created when a new user is made #It is then creating a reader to check the first column for the name entered in the main window #When it finds a match it moves along that row to find the class #(Unfinished) with open("userbase.csv") as f: for row in csv.reader(f): if row[0] == sname: sclass = str(column[2])```
Find the last window created in Maya?
I was wondering if there is any way to find the name of the last window created in Maya, knowing that I can't add any information to the window itself before that... I checked in both the cmds and API but couldn't find anything. Maybe in PyQt but I don't know much about it. I'm looking for any solution. Thanks
you can work with something like a close callback, save the needed information and restore it again def restoreLayout(self): """ Restore the layout of each widget """ settings=self.settings try: self.restoreGeometry(settings.value("geometry").toByteArray()) self.restoreState(settings.value("windowState").toByteArray()) size=settings.value('fontSize').toFloat()[0] self.setFontSize(size) except: pass def saveLayout(self): """ Save the layout of each widget Save the main window id to your data base """ settings=self.settings settings.setValue("geometry", self.saveGeometry()) settings.setValue("windowState", self.saveState()) settings.setValue("fontSize", app.font().pointSize()) def closeEvent(self, event): QtGui.QMainWindow.closeEvent(self, event) self.saveLayout() a simple case/idea to save tha main win_id and a child button_id: from functools import partial import json def close_ui(*args): win_id = args[0] if cmds.window(win_id, exists=True): cmds.deleteUI(win_id, window=True) with open('dataBase/ui/uidata.json', 'w') as outfile: json.dump(args, outfile) win = {} win["main_win"] = cmds.window() cmds.columnLayout() cmds.text( label='closing it' ) win["btn"] = cmds.button( label='Close') cmds.button(win["btn"],e=True, command=partial(close_ui, win["main_win"], win["btn"])) cmds.showWindow(win["main_win"])
Here is what I came up with, it's surely not the "cleanest" solution but it works! # List all the currently opened windows uisBefore = cmds.lsUI (wnd = True) # Execute the function which may or may not create a window func(*args, **kwargs) # List all the opened windows again uisAfter = cmds.lsUI (wnd = True) # Find all the windows that were opened after executing func() newUIs = [ui for ui in uisAfter if ui not in uisBefore]
If you create a window with the window command, you'll get back the name of the window you just created: import maya.cmds as cmds w = cmds.window() c= cmds.columnLayout() def who_am_i(*_): print "window is", w b = cmds.button('push', c=who_am_i) cmds.showWindow(w) If for some reason you don't own the code that creates the window: existing_windows = set(cmds.lsUI(type = 'window')) // make your window here new_windows = list(set(cmds.lsUI(type = 'window') - existing_windows))
Getting a variable from a Entry into a dbf
I am trying to use a entry to append the dbf part of a shapefile. So far I can only make a change to the dbf file by directly assigning the variable a value. I can only get the entry box to print a variable. What am I missing? I am using python 3.3. import shapefile from tkinter import filedialog import tkinter as tk class application: def __init__(self,window): """ Initalize the Application """ self.myentrybox = tk.Entry(window) self.myentrybox.pack() self.myentrybox.insert(0,"some default value") self.myentrybox.bind("<Return>",self.Enter) def Enter(self,event): """ Someone Pressed Enter """ print (self.myentrybox.get()) aep = 'self.myentrybox.get()' root=tk.Tk() myapp = application(root) r = shapefile.Reader('Mississippi') w = shapefile.Writer() w.fields = list(r.fields) w.field (aep, 'C', '40') i=1 for rec in r.records(): rec.append(i) i+=1 w.records.append(rec) w._shapes.extend(r.shapes()) w.save('AMissl6KM') root.mainloop()