cx_freeze error with tkinter library treectrl converting to exe setup - python

I am using python version 3.7 , I used this external library named treectrl and it works perfectly fine when I run my .py file but when I converted into exe file using cx_freeze it is giving me error NomodulleFound named tkinter. I have tried other small programs which does not use this library and I converted them in to exe file they work perfectly fine. So the idea which I got is that there is problem with this library. So I can't figure out what part this. I provided all codes , all downnload links and also error which I am getting.
https://sourceforge.net/projects/tkintertreectrl/files/
https://sourceforge.net/projects/tktreectrl/files/
Here is my code which I am converting python to exe
######################################################################
import tkinter
from TkTreectrl import *
# define some data to insert into the list:
data = {
'Joe': 1000.00,
'Jill': 738.39,
'Jack': 625.11,
'Jane': 99.99
}
root = tkinter.Tk()
# create list with scrollbars
slistbox = ScrolledMultiListbox(root)
slistbox.pack(fill='both', expand=1)
listbox = slistbox.listbox
# create columns
listbox.configure(columns=('Paid', 'Customer', 'Debt'))
#### add checkbox support to the listbox ####
# checkbox icons:
checked = tkinter.PhotoImage(data=('R0lGODlhDQANABEAACwAAAAADQANAIEAAAB/f3/f3'
'9////8CJ4yPNgHtLxYYtNbIbJ146jZ0gzeCIuhQ53NJVNpmryZqsYDnemT3BQA7'))
unchecked = tkinter.PhotoImage(data=('R0lGODlhDQANABEAACwAAAAADQANAIEAAAB/f3'
'/f39////8CIYyPNgHtLxYYtNbIrMZTX+l9WThwZAmSppqGmADHcnRaBQA7'))
# create treectrl state, element and style for the checkboxes:
listbox.state_define('Checked')
imgCheck = listbox.element_create(
type='image', image=(checked, 'Checked', unchecked, ()))
icon_style = listbox.style_create()
listbox.style_elements(icon_style,
listbox.element('select'), imgCheck, listbox.element('text'))
listbox.style_layout(icon_style, imgCheck, padx=3, pady=2)
listbox.style(0, icon_style)
# define checkbox callback that will be bound to mouse-button-1 events:
def cmd(event):
# check which element was clicked
identify = listbox.identify(event.x, event.y)
# identify might be None or look like:
# ('item', '2', 'column', '0') or
# ('item', '3', 'column', '0', 'elem', 'pyelement3')
if identify:
try:
item, column, element = identify[1], identify[3], identify[5]
if element == imgCheck:
# toggle the "checked" state
listbox.itemstate_forcolumn(item, column, '~Checked')
# do something, dependent on the current state of the checkbox
new = listbox.itemstate_forcolumn(item, column)
if new and 'Checked' in new:
# the checkbox was newly checked
print('Checked item', item, 'in column', column)
# example: debts are paid, set "Debt" to 0.00
listbox.itemelement_configure(item, listbox.column(2),
listbox.element('text'), text='0.00')
else:
# example: no payment received, set debt to stored value
print('Unchecked item', item, 'in column', column)
customer = listbox.itemelement_cget(
item, listbox.column(1),
listbox.element('text'), 'text')
debt = data[customer]
listbox.itemelement_configure(item, listbox.column(2),
listbox.element('text'), text=debt)
except IndexError:
# we did not hit the checkbox, never mind
pass
# bind the callback to button 1 events
listbox.bind('<1>', cmd)
# insert data into the list to see if this works:
for customer in data:
listbox.insert('end', '', customer, data[customer])
root.mainloop()
Here is my setup.py file
import cx_Freeze
import sys
import os
base = None
if sys.platform == 'win32':
base = "Win32GUI"
os.environ['TCL_LIBRARY'] = r"C:\Users\osama shakeel\AppData\Local\Programs\Python\Python37-32\tcl\tcl8.6"
os.environ['TK_LIBRARY'] = r"C:\Users\osama shakeel\AppData\Local\Programs\Python\Python37-32\tcl\tk8.6"
executables = [cx_Freeze.Executable("working.py", base=base, icon="icon.ico")]
cx_Freeze.setup(
name = "test",
options = {"build_exe": {"packages":["tkinter","os"], "include_files":["icon.ico",'tcl86t.dll','tk86t.dll']}},
version = "0.01",
description = "Tkinter Application",
executables = executables
)
here is my error
cx_Freeze: Python error in main script
Traceback (most recent call last):
File "C:\Users\osama
shakeel AppData\Local\Programs\Python Python37-32\lib \site
-packages\cx_Freeze\initscripts _startup_.py", line 40, in run
module.runo
File "C:\Users\osama
shakeel AppData\Local\Programs\Python Python37-32\lib\site
-packages\cx_Freeze\initscripts\Console.py", line 37, in run
exec(code, [name__ main__'})
File "working.py", line 5, in <module>
ModuleNotFoundError: No module named 'tkinter
ок

Related

Using a Tkinter button input to pass as argument

I'm using tkinter to create an option menu, where choosing an option will call a function specific to each option. However, I'm unable to figure out exactly how to do that.
This is the code that is currently being used.
import pandas as pd
import os
import matplotlib.pyplot as plt
#below code imports file needed at the moment
import tkinter as tk
from tkinter import *
from tkinter import filedialog
import pandas as pd
import os
import matplotlib.pyplot as plt
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename() #will open file from any location, does not need to be in the same place as the code script
df = pd.read_csv(file_path)
df.rename(columns={'Unnamed: 0':'Type'}, inplace=True) #renames the first unnamed column to type (drug available (DA) or not available (NA)
df.dropna(how = 'all', axis = 1, inplace = True) #drops the empty column present in each dataset, only drops it if the whole column is empty
##plotting functions for both active and inactive pokes
def ActivePokes(df):
plt.rcParams["figure.figsize"] = (12,7.5)
df.plot()
plt.xticks(range(0,len(df.Type)), df.Type)
plt.ylabel("Number of Active Pokes")
plt.xlabel("Sessions")
plt.title("Number of Active Pokes vs Drug Availability")
plt.show()
def InactivePokes(df):
plt.rcParams["figure.figsize"] = (12,7.5)
df.plot()
plt.xticks(range(0,len(df.Type)), df.Type)
plt.ylabel("Number of Inactive Pokes")
plt.xlabel("Sessions")
plt.title("Number of Inactive Pokes vs Drug Availability")
plt.show()
def show(df):
if variable == options[1]:
button[command] = ActivePokes(df)
elif variable == options[2]:
button[command] = InactivePokes(df)
else:
print("Error!")
options = [ "Choose Option",
"1. Active pokes, Drug Available and No Drug Available sessions",
"2. Inactive pokes, Drug Available and No Drug Available sessions"]
button = Tk()
button.title("Dialog Window")
button.geometry('500x90')
variable = StringVar(button)
variable.set(options[0]) #default value, might change and edit as time passes
option = OptionMenu(button, variable, *options, command = show)
option.pack()
button.mainloop()
I know the show() function is where the issue lies, but I'm not entirely sure how to rectify it.
The other comments and answer address problems with creating two Tk objects and using .get() with a StringVar.
The command = show callback is passed the string value of the item chosen. In your show( df ) when called from the Optionmenu will have df equal to one of the options. It won't be a pandas dataframe. Pure tkinter example below.
import tkinter as tk
root = tk.Tk()
root.geometry( '100x100' )
var = tk.StringVar( value = 'Option A' )
def on_choice( chosen ):
""" The callback function for an Optionmenu choice.
chosen: The text value of the item chosen.
"""
print( chosen, end = " : " )
print( ' or from the StringVar: ', var.get() )
opt_list = [ 'Option A', 'Option B', 'Option C' ]
options = tk.OptionMenu( root, var, *opt_list, command = on_choice )
options.grid()
root.mainloop()
First problem, you have created a tk instance called root, and then another one called button,why? perhaps you want button to be a tk.Button and not a tk instance? Not sure what is the intention here.
second, what is it command variable you want to change for button? (button[command]). if button where a tk.button, then perhaps you wanted to do button['command'] = ..., however, if the intention is to call the pokes functions why not calling them right away?
third problem is here:
def show(df):
if variable == options[1]:
button[command] = lambda: ActivePokes(df)
elif variable == options[2]:
button[command] = lambda: InactivePokes(df)
else:
print("Error!")
change variable for variable.get()

Saving the value of a checkbox if it's on Tkinter

I need help. While I'm saving the value of "box" it just writes ".!checkbutton" instead of the value I want. Why does this happen and how to fix it.
So I want it to write the onvalue in the txt instead of .!checkbutton if the box is ticked
how to fix this
Also if there is a way to make the checkbox bigger I would appreciate it :)
# -*- coding: utf8 -*-
from tkinter import *
from tkinter import messagebox
import os
root = Tk()
root.title('Feedback')
root.geometry("400x400")
organizerlist = [
"213",
"1231",
"123",
"123",
"123",
"123",
"123",
"."
]
eventsnames = [
"Rocket League"
]
def run():
# getting the name
filename = filename_ent.get()
if filename == '':
# to show an error that boxes are empty
messagebox.showerror(
'File exists', 'File already exists, try some other name thas is not used before')
if os.path.exists(f'{filename}.txt'):
# to show an error if the file already exists
messagebox.showerror(
'File exists', 'File already exists, try some other name not used before')
else:
# to open the file for python
new = open(f'{filename}.txt', '+w', encoding='utf-8')
# to write the name and email inside the file
new.write(f'''Admin of the event: {clicked.get()}\n{responsible.get()} \n{box}''')
lfilename.config(text=f'The Feedback has been written successfully!') # to change the label to the name
os.startfile(f'{filename}.txt') # to open the file in a new window
lfilename = Label(root,text="What do you want to call the file?", font = ("helvatica, 14"))
lfilename.grid(row=0, column=0)
filename_ent = Entry(root)
filename_ent.grid(row=1, column=0)
clicked = StringVar()
clicked.set("Who is Admin?")
drop = OptionMenu(root, clicked, "User", "#User2", "#User3", "#User")
drop.grid(row=2, column=0)
eventname = StringVar()
eventname.set("Which event was it?" )
eventname_drop = OptionMenu(root, eventname, *eventsnames, )
eventname_drop.grid(row=3,column=0, )
responsible = StringVar()
responsible.set("Who is the responsible?")
responsible_drop = OptionMenu(root, responsible, *organizerlist)
responsible_drop.grid(row=4,column=0)
responsible_drop.config(width=30, font=("helvatica", 14))
var = StringVar()
box = Checkbutton(root,text="test", variable=var, onvalue="Working", offvalue="Not Working")
box.grid(row=3,column=3)
b = Button(root, text='Done', command=run)
b.grid(row=20, column=0)
root.mainloop()
Try changing function to to below:
def run():
# getting the name
filename = filename_ent.get()
if filename == '':
# to show an error that boxes are empty
messagebox.showerror('Empty Box', 'Make sure to to fill the filename box.')
elif os.path.exists(f'{filename}.txt'):
# to show an error if the file already exists
messagebox.showerror(
'File exists', 'File already exists, try some other name not used before')
else:
# to open the file for python
new = open(f'{filename}.txt', '+w', encoding='utf-8')
# to write the name and email inside the file
new.write(f'Admin of the event: {clicked.get()}\n{responsible.get()} \n{var.get()}')
lfilename.config(text=f'The Feedback has been written successfully!') # to change the label to the name
os.startfile(f'{filename}.txt') # to open the file in a new window
In short, you forgot to call var.get() and you said box instead, which was the checkbutton itself.
Also Ive changed your second if statement to elif because having multiple if will lead to the second if getting executed, no matter what the conditions on first if was. Just try saying an empty filename with your code, and you can see the problem.
Hope this helped, do let me know if any errors or doubts.

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])```

Cannot get LabelFrame widget to display on ttk notebook (python 3.5.1)

I have an application in which the (tkinter) LabelFrame widget on the tab of a ttk Notebook will not update itself. In a much simplified version of that program (code extracts below) the widget will not even appear on the GUI.
Everything else on the GUI works properly, including updating the tab titles, the application title (and icon) and updating the Label, Checkbutton and Radiobutton widgets on all notebook tabs. Using the ttk versions (e.g. ttk.LabelFrame) to create those widgets did not fix the issue. I also tried using “update_idletasks” (some think this as a kludge) immediately after updating the widget attributes without success.
In the real application the text of all GUI widgets change according to the state of a “choose language” widget on the same GUI (for details, see: Need Python/tkinter GUI to dynamically update itself (for a multi-lingual GUI)). It’s known that all GUI text values (the WidgetName["text”] attribute), including the missing LabelFrame, are being correctly updated to match the state of that widget.
Is there something “special” about LabelFrame widgets on Notebook tabs? What (probably simple) thing am I overlooking?
Also, any confirmation/denial by others will help determine if the problem is unique to my system - a distinct possiblity since my machine is administered by corporate IM (who don't have the best record when handling the needs of unusual users like me).
Thanks
The following is a complete example of the problem. When run, the LabelFrame widget (which should appear at (0, 0) of Tab 1) does not appear. Clicking on the "language" widget causes everything else to display text in the language selected by the "language" widget.
From “LanguageInUse.py” the code that switches languages:
import sys
c_cedille_lower = "\u00E7" # UTF 8/16 (code page 863?) French character
e_circumflex_lower = "\u00EA"
English = 'English' # string shown on GUI
Francais = 'Fran' + c_cedille_lower + 'ais' # string shown on GUI
DefaultLanguage = Francais
DefaultLanguage = English # comment out this line to use French
user_language = DefaultLanguage # set up language shown on GUI
# Define all language-dependent GUI strings (as "Application-Level" globals)
ComplianceMessage = None
ReportTab1Title = None
ReportTab2Title = None
XCheckbuttonMessage = None
XLabelFrameMessage = None
XLabelMessage = None
XRadioButtonMessage = None
'''=========================================================================='''
def SetGuiLanguage( user_language ) :
global ComplianceMessage, LanguagePrompt
global ReportTab1Title, ReportTab2Title
global XLabelFrameMessage, XCheckbuttonMessage, XLabelMessage, XRadioButtonMessage
if ( user_language == English ):
LanguagePrompt = "Language"
ReportTab1Title = "Message Counts"
ReportTab2Title = "Communications Compliance"
XLabelFrameMessage = "LabelFrame"
XCheckbuttonMessage = "Checkbox"
XLabelMessage = "Label"
XRadioButtonMessage = 'Radiobutton'
ComplianceMessage = "Compliance (engish)"
elif ( user_language == Francais ):
LanguagePrompt = "Langage"
ReportTab1Title = "Comtes de message"
ReportTab2Title = "Compliance Communications"
XLabelFrameMessage = "LabelFrame en " + Francais
XCheckbuttonMessage = "Checkbox en " + Francais
XLabelMessage = "Label en " + Francais
XRadioButtonMessage = "Radiobutton en " + Francais
ComplianceMessage = "Compliance - " + Francais
else:
print (' An unknown user language was specified' )
sys.exit()
return
'''=========================================================================='''
SetGuiLanguage( user_language ) # initialize all tkinter strings at startup
'''========================== End of File ================================'''
From “SelectReports.py”) the code that builds the notebook:
from tkinter import Checkbutton, Radiobutton, Label, LabelFrame, Frame
from tkinter import ttk
import LanguageInUse
# Locally defined entities importable by other modules (often
# Tkinter Application level objects whose language can be changed)
ComplianceMessageText = None
NotebookFrame = None
XCheckbutton = None
XLabel = None
XLabelFrame = None # NOT APPEARING ON THE GUI
XRadiobutton = None
'''=========================================================================='''
def TabbedReports( ParentFrame ) :
global ComplianceMessageText, NotebookFrame
global SelectReportFrame, UplinkFileWarningText
global XCheckbutton, XLabel, XLabelFrame, XRadiobutton
# Builds the notebook and it's widgits
NotebookFrame = ttk.Notebook( ParentFrame )
NotebookFrame.grid( row = 0, column = 1 )
Tab1Frame = Frame( NotebookFrame )
Tab2Frame = Frame( NotebookFrame )
NotebookFrame.add( Tab1Frame )
NotebookFrame.add( Tab2Frame )
# Create widgets on Tab 1
XLabelFrame = LabelFrame( Tab1Frame ) # NOT APPEARING ON GUI
XCheckbutton = Checkbutton( Tab1Frame )
XLabel = Label( Tab1Frame )
XRadiobutton = Radiobutton( Tab1Frame )
XLabelFrame.grid( row = 1, column = 0 ) # NOT ON GUI
XCheckbutton.grid( row = 1, column = 1 )
XLabel.grid( row = 2, column = 0 )
XRadiobutton.grid( row = 2, column = 1 )
XLabelFrame.configure( text = LanguageInUse.XLabelFrameMessage ) # NOT ON GUI
XCheckbutton.configure( text = LanguageInUse.XCheckbuttonMessage )
XLabel.configure( text = LanguageInUse.XLabelMessage )
XRadiobutton.configure( text = LanguageInUse.XRadioButtonMessage )
# .tab() gives same effect as .configure() for other widget types
NotebookFrame.tab( 0 , text = LanguageInUse.ReportTab1Title )
NotebookFrame.tab( 1 , text = LanguageInUse.ReportTab2Title )
# Create the only widget on Tab 2 (uses other method to specify text)
ComplianceMessageText = Label( Tab2Frame )
ComplianceMessageText.grid( row = 0, column = 0 )
ComplianceMessageText['text'] = LanguageInUse.ComplianceMessage
return
From “ChangeLanguageOnGui.py” the code that updates all notebook widgets:
import sys, os
from tkinter import StringVar, Radiobutton, PhotoImage
#from TkinterRoot import root
import LanguageInUse
import SelectReports
'''=========================================================================='''
def ChangeLanguageOnGui() :
SelectReports.XLabelFrame.configure( text = LanguageInUse.XLabelFrameMessage ) # NOT ON GUI
SelectReports.XCheckbutton.configure( text = LanguageInUse.XCheckbuttonMessage )
SelectReports.XLabel.configure( text = LanguageInUse.XLabelMessage )
SelectReports.XRadiobutton.configure( text = LanguageInUse.XRadioButtonMessage )
# .tab() gives the same effect as .configure() for other widget types
SelectReports.NotebookFrame.tab( 0 , text = LanguageInUse.ReportTab1Title )
SelectReports.NotebookFrame.tab( 1 , text = LanguageInUse.ReportTab2Title )
SelectReports.ComplianceMessageText['text'] = LanguageInUse.ComplianceMessage
'''=========================================================================='''
def SetUpGuiLanguage( LanguageFrame ) :
GUI_Language = StringVar( value = LanguageInUse.user_language )
#---------------------------------------------------------------------------
def switchLanguage():
LanguageInUse.user_language = GUI_Language.get()
LanguageInUse.SetGuiLanguage( LanguageInUse.user_language )
ChangeLanguageOnGui()
return
#---------------------------------------------------------------------------
UsingEnglish = Radiobutton( LanguageFrame, indicatoron = False,
variable = GUI_Language,
command = lambda: switchLanguage(),
value = LanguageInUse.English )
UsingFrancais = Radiobutton( LanguageFrame, indicatoron = False,
variable = GUI_Language,
command = lambda: switchLanguage(),
value = LanguageInUse.Francais )
UsingEnglish.grid( row = 0, column = 0 )
UsingFrancais.grid( row = 1, column = 0 )
UsingEnglish.configure( text = LanguageInUse.English )
UsingFrancais.configure( text = LanguageInUse.Francais )
From "TkinterRoot.py" the code that makes root importable everywhere (explictly importing this avoided problems such as IntVar() being unavailable during the intitialization phase of other modules):
from tkinter import Tk # possibly the worlds shortest useful python module
root = Tk() # makes root an importable "Application Level" global
And finally "A.py", the mainline file:
from TkinterRoot import root
from tkinter import LabelFrame
from tkinter import ttk
import ChangeLanguageOnGui, LanguageInUse, SelectReports, sys
LanguageFrame = None
if __name__ == "__main__":
LanguageChoice = LanguageInUse.English
if ( LanguageChoice == LanguageInUse.English ) :
LanguageInUse.user_language = LanguageChoice
elif ( LanguageChoice == 'Francais' ) :
LanguageInUse.user_language = LanguageInUse.Francais
else :
print( "Unknown Language: " + LanguageChoice )
sys.exit()
mainframe = ttk.Frame( root )
mainframe.grid( row = 0, column = 0 )
LanguageFrame = LabelFrame( mainframe, text = LanguageInUse.LanguagePrompt )
LanguageFrame.grid( row = 0, column = 0 )
ChangeLanguageOnGui.SetUpGuiLanguage( LanguageFrame )
SelectReports.TabbedReports( mainframe )
try:
root.mainloop()
except:
print( 'Exception Occurred' )
sys.exit()
The Environment is 64-bit Python 3.5.1, 64-bit Win 7 Enterprise SP 1, 64-bit Eclipse Mars 2 (the Java EE IDE edition) running 64-bit PyDev 5.1.2.201606231256. The "one user" (no admin rights) version of Pydev was used, this required Microsoft patch KB2999226 (part of Win10) to run on Win7. Eventual target distribution is a 32-bit Windows app (so it can run on 32 & 64 bit Windows) - and if/when time permits - Linux.
There’s one minor complication to keep in mind: In the real program several packages are being used. Inside each package each function is isolated inside its own file. All objects (e.g. the tkinter widgets) that must be externally visible (or need be shared amongst the package’s files) are declared in the package’s _ _ init.py _ _ file. Functions that must be externally visible are explicitly imported into _ _ init.py _ _ by using relative imports (e.g. “from .Function1 import Function1” ).
Your title is misleading because you place the LabelFrame in a Frame, not directly on a Notebook tab. Your problem is that the labelframe does not appear in its parent frame. The Notebook is irrelevant and all associated code should have been deleted before posting.
Even the frame is irrelevant in that the same problem arises when putting the labelframe directly in root. Here is minimal code that demonstrate both the problem and a solution.
from tkinter import Tk
from tkinter import ttk
root = Tk()
lf1 = ttk.LabelFrame(root, text='labelframe 1')
lf2 = ttk.LabelFrame(root, text='labelframe 2', width=200, height=100)
lf1.pack()
lf2.pack()
I ran this on Win 10 with 3.6a2, which comes with tk 8.6.4. Only lf2 is visible because the default size of a labelframe, as with a frame, is 0 x 0. A non-default size arises either from explicit sizing or from contents. Somewhat surprisingly, the label does not count as content and does not force a non-default size. I reproduced the same result with the labelframe in a frame (your situation) and on a tab.

inserting path in the entry box in Python GUI

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)

Categories