Cant get code to execute in thread with Tkinter GUI - python

Here is the code it is supposed to scan and enumerate a directory and make hashes of whatever files it finds and append them to a dict the code all works separately but I cant get the hashing part to trigger within the threaded code there is no error
import threading
import tkinter as tk
import tkinter.ttk as ttk
import hashlib
import glob
class global_variables:
def __init__(self):
pass
DirSelected = ''
Manifest = []
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Progress bar example")
self.button = tk.Button(self, text="Start", command=self.start_action)
self.button.pack(padx=10, pady=10)
def start_action(self):
self.button.config(state=tk.DISABLED)
t = threading.Thread(target=self.contar)
t.start()
self.windows_bar = WinProgressBar(self)
def contar(self):
directories_scanned = [str, 'File,Md5!'] # , separator value ! delineator adds new line
target_dir = '/Users/kyle/PycharmProjects/' # this wont run
files = glob.glob(target_dir + '/**/*.*', recursive=True) # Line adds search criteria aka find all all to the
# directory for GLOB
for file in files:
with open(file, "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
directories_scanned.append(
file + ',' + str(file_hash.hexdigest() + '!')) # Appends the file path and Md5
global_variables.Manifest = directories_scanned
for x in range(len(global_variables.DirSelected)): # testing to view files TODO REMOVE this
print(global_variables.DirSelected[x])
for i in range(10): #to here
print("Is continuing", i)
print('stop')
self.windows_bar.progressbar.stop()
self.windows_bar.destroy()
self.button.config(state=tk.NORMAL)
class WinProgressBar(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.title("Progress")
self.geometry("300x200")
self.progressbar = ttk.Progressbar(self, mode="indeterminate")
self.progressbar.place(x=30, y=60, width=200)
self.progressbar.start(20)
if __name__ == "__main__":
global_variables()
app = App()
app.mainloop()
print("Code after loop")
for x in range(len(global_variables.DirSelected)): # testing to view files TODO REMOVE this
print(global_variables.DirSelected[x])
No errors can be shown this time the code will run

It works fine for me. I think you just were checking the wrong variable DirSelected which was in fact an empty string. (see my code)
Also, I moved your WinProgressBar so it is available when the thread is executing. (was getting an exception on this).
import threading
import tkinter as tk
import tkinter.ttk as ttk
import hashlib
import glob
class global_variables:
def __init__(self):
pass
DirSelected = ''
Manifest = []
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Progress bar example")
self.button = tk.Button(self, text="Start", command=self.start_action)
self.button.pack(padx=10, pady=10)
def start_action(self):
self.button.config(state=tk.DISABLED)
self.windows_bar = WinProgressBar(self)
t = threading.Thread(target=self.contar)
t.start()
def contar(self):
directories_scanned = [str, 'File,Md5!'] # , separator value ! delineator adds new line
target_dir = '/home/jsantos/workspace/blog.santos.cloud/' # this wont run
files = glob.glob(target_dir + '/**/*.*', recursive=True) # Line adds search criteria aka find all all to the
# directory for GLOB
for file in files:
with open(file, "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
directories_scanned.append(
file + ',' + str(file_hash.hexdigest() + '!')) # Appends the file path and Md5
global_variables.Manifest = directories_scanned
for x in range(len(global_variables.Manifest)): # testing to view files TODO REMOVE this
print(global_variables.Manifest[x])
for i in range(10): #to here
print("Is continuing", i)
print('stop')
self.windows_bar.progressbar.stop()
self.windows_bar.destroy()
self.button.config(state=tk.NORMAL)
class WinProgressBar(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.title("Progress")
self.geometry("300x200")
self.progressbar = ttk.Progressbar(self, mode="indeterminate")
self.progressbar.place(x=30, y=60, width=200)
self.progressbar.start(20)
if __name__ == "__main__":
global_variables()
app = App()
app.mainloop()
print("Code after loop")
for x in range(len(global_variables.Manifest)): # testing to view files TODO REMOVE this
print(global_variables.Manifest[x])

Related

pass tkinter openfilename to a instance variable

Checked:
python pass variable tkinter
Tkinter - How to pass instance variable to another class?
and other web resources but didn't find a solution.
I have a Tkinter button to open file:
import tkinter as tk
from tkinter import filedialog as fd
from myClass import my_function
class select_file:
def __init__(self):
self.root = tk.Tk()
self.filename = ""
tk.Button(self.root, text="Browse", command=self.open).pack()
self.root.mainloop()
def open(self):
filetypes = (('LOG files', '*.LOG'), ('All files', '*.*'))
self.filename = fd.askopenfilename(title='open LOG file', filetypes=filetypes)
self.root.destroy()
print(self.filename)
return self.filename
and that's work fine since I can get the file path in right way.
Output:
C:/Users/xxxx/xxxxx/Dataset/SC180918.LOG
My question is how I can pass the selected filename as instance variable to other function within same project but in another file (myClass.py):
class my_function:
log_frame = pd.DataFrame()
def __init__(self, file):
self.file = file
def create_df(self):
myClass.log_frame = pd.read_table(self.file, sep=';', index_col='TimeStamp', parse_dates=True)
return myClass.log_frame
My task is to pass the file to create_df.
I tried several code I will not post to avoid confusion and not working code.
As the file is important, I generated two python files as below:
myClass.py:
class my_function:
def __init__(self, file):
self.file = file
def create_df(self):
print("filename in my_function is ",self.file)
testMe.py:
import tkinter as tk
from tkinter import filedialog as fd
from myClass import my_function
class select_file:
def __init__(self):
self.root = tk.Tk()
self.filename = ""
tk.Button(self.root, text="Browse", command=self.open).pack()
self.root.mainloop()
def open(self):
filetypes = (('LOG files', '*.LOG'), ('All files', '*.*'))
self.filename = fd.askopenfilename(title='open LOG file', filetypes=filetypes)
self.root.destroy()
print("filename in select_file is ",self.filename)
return self.filename
sfClass = select_file() # select filename by Browse
filename = sfClass.filename # get filename from the class
mfClass = my_function(filename) # pass it to the class
mfClass.create_df()
here is the output if I select testMe.py file:
filename in select_file is C:/Users/XXX/XXX/SOquestions/testMe.py
filename in my_function is C:/Users/XXX/XXX/SOquestions/testMe.py
as a result, filename has been successfully passed to the my_function.
I tested as below as well:
print(mfClass.file)
it prints: C:/Users/XXX/XXX/SOquestions/testMe.py
I would do as following;
sfClass = select_file() # select filename by Browse
filename = sfClass.filename # get filename from the class
mfClass = my_function(filename) # pass it to the class

after() hangs the output window

I am trying to build a real time project where the status gets updated every second, so some part of code repeats continuously. when i want to change the information which has to be get updated i will just click on new button which gives me the first window where i can update the new information. but by doing so gives me the following error. if i use after() instead of threading, the error wont be there but the output window gets hanged.Please help me with the idea to resolve this. Thank you.
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\threading.py", line 1177, in run
self.function(*self.args, **self.kwargs)
File "C:/Users/Desktop/Tool/t.py", line 47, in ae
self.treeview.insert('', 'end',image=self._img, value=(a))
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\tkinter\ttk.py", line 1370, in insert
res = self.tk.call(self._w, "insert", parent, index, *opts)
_tkinter.TclError: invalid command name ".!treeview"
Code where i have problem with:
def aaa(self):
num_threads = 5 * multiprocessing.cpu_count()
p = multiprocessing.dummy.Pool(num_threads)
p.map(self.ping_func, [x for x in Demo2.t1])
self.process_incoming()
#threading.Timer(1.0, self.aaa).start()-this gives the error while pressing new button and updating information
self.master.after(100, self.aaa) #it hangs the output window
Sample code:
import multiprocessing.dummy
import multiprocessing
import os
import socket
import sys
import subprocess
import re
import time
import threading
import tkinter.messagebox
from tkinter import ttk
import queue
from tkinter import *
class Demo1: #window 1
data=[]
def __init__(self, master):
self.master = master
self.t=tkinter.Text(self.master,height=20,width=50)
self.t.grid(row=1, column=1)
self.button = tkinter.Button(self.master,height=3,width=10, text="OK", command = self.new_window)
self.button.grid(row=2,column=1)
def new_window(self):
self.inputValue=self.t.get("1.0",'end-1c')
Demo1.data=self.inputValue.split("\n")
self.master.destroy() # close the current window
self.master = tkinter.Tk() # create another Tk instance
self.app = Demo2(self.master) # create Demo2 window
self.master.mainloop()
class Demo2: #window 2
value = []
display = []
num=0
def __init__(self, master):
self.master = master
self.queue = queue.Queue()
Demo2.value = Demo1.data
self.button = tkinter.Button(self.master,height=2,width=11, text="new",command=self.new).place(x=0,y=0)
self.label = tkinter.Label(self.master, text="monitor", font=("Arial",20)).grid(row=0, columnspan=3)
cols = ('aa','bb')
self.treeview = ttk.Treeview(self.master, columns=cols)
for col in cols:
self.treeview.heading(col, text=col)
self.treeview.column(col,minwidth=0,width=170)
self.treeview.grid(row=1, column=0)
self._img=tkinter.PhotoImage(file="green1.gif")
self.aaa()
def aaa(self):
num_threads = 5 * multiprocessing.cpu_count()
p = multiprocessing.dummy.Pool(num_threads)
p.map(self.ping_func, [x for x in Demo2.value])
self.process_incoming()
#threading.Timer(1.0, self.aaa).start()
self.master.after(100, self.aaa)
def ping_func(self,ip): #Ping every ip and append the result
ping_result = []
pingCmd = "ping -n 1 -w 1000 " + ip
childStdout = os.popen(pingCmd)
result = (childStdout.readlines())
childStdout.close()
ping_result.append(ip)
if(any('Reply from' in i for i in result)):
ping_result.append("success")
else:
ping_result.append("failed")
self.queue.put(ping_result) #Thread value to queue
def process_incoming(self): #add the ping result to treeview
while self.queue.qsize():
try:
if Demo2.num<len(Demo1.data):
self._img=tkinter.PhotoImage(file="green1.gif")
self._img1=tkinter.PhotoImage(file="red.gif")
msg = self.queue.get_nowait()
Demo2.display.append(msg) #adding queue value to variable(display)
if(len(Demo2.display)==len(Demo1.data)):
self.treeview.insert("","end",values=(0,0,0,0,0))
self.treeview.delete(*self.treeview.get_children())
for i,(a,b) in enumerate(Demo2.display):
if(Demo2.display[i][1]=='success' ):
self.treeview.insert('', 'end',image=self._img, value=(a,b))
else:
self.treeview.insert('', 'end',image=self._img1, value=(a,b))
Demo2.num=Demo2.num+1
Demo2.display.clear()
else:
Demo2.display.clear()
Demo2.num=0
except queue.Empty: # Shouldn't happen.
pass
def periodic_call(self):
self.master.after(200, self.periodic_call) # checking its contents periodically
self.process_incoming()
if not self.running:
import sys
sys.exit(1)
def new(self):
self.master.destroy() # close the current window
self.master = tkinter.Tk() # create another Tk instance
self.app = Demo1(self.master) # create Demo2 window
self.master.mainloop()
def main():
root = tkinter.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
Main problem is that ping -w 1000 need a lot of time to run but Pool.map() waits for all results. You could even run results = p.map(...) without queue (but with return result) but it could also block tkinter
You may use map_async() to run it without waiting for results.
I also use starmap (or rather starmap_async()) to send two arguments ip, queue to every process.
I also made other changes - ie. rename variables, move some code to __init__ to create only once (images, Pool, Queue). I also send list of IP to other window as argument Window2(master, data) and back Window1(master, data) - so I can edit this list.
BTW: because I run on Linux so I changed arguments for ping and check different text to test if it get answer.
import os
import multiprocessing.dummy
import queue
import tkinter as tk
import tkinter.ttk as ttk
# --- classes ---
class Window1:
def __init__(self, master, data=None):
self.master = master
self.data = data
if self.data is None:
self.data = []
self.text = tk.Text(self.master, height=20, width=50)
self.text.grid(row=1, column=1)
self.button = tk.Button(self.master, height=3, width=10, text="OK", command=self.new_window)
self.button.grid(row=2, column=1)
# put self.data in Text
#for item in self.data:
# self.text.insert('end', item + '\n')
self.text.insert('end', '\n'.join(self.data))
def new_window(self):
text = self.text.get('1.0', 'end')
# remove empty lines
self.data = [item.strip() for item in text.split("\n") if item.strip()]
self.master.destroy()
root = tk.Tk()
Window2(root, self.data)
root.mainloop()
class Window2:
def __init__(self, master, data):
self.master = master
# keep list
self.data = data
# create dictionary for results
self.results = {ip: [ip, '???'] for ip in self.data}
self.button = tk.Button(self.master, height=2, width=11, text='New', command=self.new)
self.button.grid(row=0, column=0, sticky='w')
self.label = tk.Label(self.master, text='monitor', font=("Arial", 20))
self.label.grid(row=0, column=1)
cols = ('IP','Result')
self.treeview = ttk.Treeview(self.master, columns=cols)
for col in cols:
self.treeview.heading(col, text=col)
self.treeview.column(col,minwidth=0,width=170)
self.treeview.grid(row=1, column=0, columnspan=3)
# create only once
self._image_green = None # tk.PhotoImage(file="green1.gif")
self._image_red = None # tk.PhotoImage(file="red.gif")
# to reduce number of processes for small `data`
n = min(5, len(self.data))
# create only once
self.queue = queue.Queue()
self.num_threads = n * multiprocessing.cpu_count()
self.p = multiprocessing.dummy.Pool(self.num_threads)
# to stop `after()`
self.running = True
# run first time
self.update_treeview() # to display it before running processes
self.run_processes()
self.processes_incoming() # first create window to display it faster
def run_processes(self):
if self.running:
self.p.starmap_async(self.ping, [(ip, self.queue) for ip in self.data])
self.after_ID2 = self.master.after(500, self.run_processes)
def ping(self, ip, queue):
#print('start ping:', ip)
#cmd = 'ping -n 1 -w 3 ' + ip
cmd = 'ping -w 1 ' + ip # Linux
child_stdout = os.popen(cmd)
result = child_stdout.readlines()
child_stdout.close()
#print('end ping:', ip)
#if any('Reply from' in line for line in result):
if any('bytes from' in line for line in result): # Linux
value = [ip, 'success']
else:
value = [ip, 'failed']
queue.put(value)
def update_treeview(self):
self.treeview.delete(*self.treeview.get_children())
for ip in self.data:
ip, value = self.results[ip]
if value == 'success':
image = self._image_green
elif value == 'failed':
image = self._image_red
else:
image = None
#self.treeview.insert('', 'end', image=image, value=(ip, valueb))
self.treeview.insert('', 'end', value=(ip, value))
def processes_incoming(self):
if self.running:
# get all from queue
new_values = False
while self.queue.qsize():
#while not self.queue.empty:
data = self.queue.get_nowait()
ip, value = data
self.results[ip] = data
new_values = True
# update only if new values
if new_values:
self.update_treeview()
# repeate after 100ms
self.after_ID1 = self.master.after(100, self.processes_incoming)
def new(self):
# to stop all `after()`
self.running = False
self.master.after_cancel(self.after_ID1)
self.master.after_cancel(self.after_ID2)
self.master.destroy()
root = tk.Tk()
Window1(root, self.data)
root.mainloop()
# --- functions ---
def main():
examples = [
'127.0.0.1', # localhost
'10.0.0.1', # IP in local network
'192.168.0.1', # IP in local network
'8.8.8.8', # Google DNS
'8.8.4.4', # Google DNS
]
root = tk.Tk()
Window1(root, examples)
root.mainloop()
# --- main ---
if __name__ == '__main__':
main()

Use Tkinter to Open file, run script and export file

I would like to create a pyton script that takes an excel file (provided by the user), run a script, and save this excel file (with a file name provided by the user).
I would like to implement some buttons using Tkinter to enable non-programmers to easily use my algorithm.
I tried to create a ''load data'' and ''display data'' button (I took a code online) that both work.
However I didn't manage to run the script on the database imported (as I don't know how to access it)
I didnt manage to create a button that enables the user to choose the name of the file they want to save it to.
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror
import pandas as pd
import csv
# --- classes ---
class MyWindow:
def __init__(self, parent):
self.parent = parent
self.filename = None
self.df = None
self.text = tk.Text(self.parent)
self.text.pack()
self.button = tk.Button(self.parent, text='LOAD DATA', command=self.load)
self.button.pack()
self.button = tk.Button(self.parent, text='DISPLAY DATA', command=self.display)
self.button.pack()
self.button = tk.Button(self.parent, text='DISPLAY DATA', command=self.display)
self.button.pack()
def load(self):
name = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xslm', '*.xlsx'))])
if name:
if name.endswith('.csv'):
self.df = pd.read_csv(name)
else:
self.df = pd.read_excel(name)
self.filename = name
display directly
self.text.insert('end', str(self.df.head()) + '\n')
def display(self):
# ask for file if not loaded yet
if self.df is None:
self.load_file()
# display if loaded
if self.df is not None:
self.text.insert('end', self.filename + '\n')
self.text.insert('end', str(self.df.head()) + '\n')
#def script_python(self):
# self.df=self.df.iloc[:, :-1]
#this is not my original script
#def file_save(self):
# savefile = asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),
# ("All files", "*.*") ))
# --- main ---
if __name__ == '__main__':
root = tk.Tk()
top = MyWindow(root)
root.mainloop()
My python script that do analysis on the excel file works, so I just put a very simple python script to make your life easier.
Thank you
I'm new at Tkinter and not used to classes and dictionaries. thanks for your help
I've modified your code, adding a button to run your script and a button to save the data (I've tried to keep the rest as close to your original code as possible):
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror
import pandas as pd
import csv
# --- classes ---
class MyWindow:
def __init__(self, parent):
self.parent = parent
self.filename = None
self.df = None
self.text = tk.Text(self.parent)
self.text.pack()
# load data button
self.load_button = tk.Button(self.parent, text='LOAD DATA', command=self.load)
self.load_button.pack()
# display data button
self.display_button = tk.Button(self.parent, text='DISPLAY DATA', command=self.display)
self.display_button.pack()
# run script button
self.script_button = tk.Button(self.parent, text='RUN SCRIPT', command=self.script_python)
self.script_button.pack()
# save data button
self.save_button = tk.Button(self.parent, text='SAVE DATA', command=self.file_save)
self.save_button.pack()
def load(self):
name = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xslm', '*.xlsx'))])
if name:
if name.endswith('.csv'):
self.df = pd.read_csv(name)
else:
self.df = pd.read_excel(name)
self.filename = name
# display directly
self.text.insert('end', str(self.df.head()) + '\n')
def display(self):
# ask for file if not loaded yet
if self.df is None:
self.load_file()
# display if loaded
if self.df is not None:
self.text.insert('end', self.filename + '\n')
self.text.insert('end', str(self.df.head()) + '\n')
def script_python(self):
# replace this with the real thing
self.df = self.df.iloc[:, :-1]
def file_save(self):
fname = asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),
("All files", "*.*")))
# note: this will fail unless user ends the fname with ".xlsx"
self.df.to_excel(fname)
# --- main ---
if __name__ == '__main__':
root = tk.Tk()
top = MyWindow(root)
root.mainloop()

display a log file in real time with tkinter text field (python2.7)

I am trying to write a GUI that can display the log file in real time (tail -f log). The new line from the log file can be printed out into the terminal, but it cannot be loaded into the text field (line #). Can any one tell me why it won't put back to the text field?
from Tkinter import *
import os, time
import tkFileDialog
class Controller(object):
def __init__(self, master):
""" Main interface:
master - the top level window
"""
self._master = master
frame1 = Frame(self._master)
label = Label(self._master, text="Select a Log File")
label.pack(side=TOP)
currentLogfile = StringVar(self._master)
LogfileList = [f for f in os.listdir('.') if os.path.isfile(f)]
currentLogfile.set(LogfileList[0])
chooseLog = OptionMenu(self._master, currentLogfile, *LogfileList, command = self.file_open)
chooseLog.config(width = "300")
chooseLog.pack(side=TOP)
self._master.config(menu=chooseLog)
self._Text=Text(frame1, bg = 'black', fg = 'white')
self._Text.pack(side = TOP,fill=BOTH, expand = True,pady=20)
w = Scrollbar(self._Text)
w.pack(side=RIGHT, fill=Y)
frame1.pack(side=TOP, fill=BOTH, padx=5,expand=True)
def file_open(self,filename):
#clear text field
self._Text.delete('1.0', END)
with open(filename,'r') as f:
loglines = follow(f)
for line in loglines:
#print line
self._Text.insert(END,line)
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(5)
continue
yield line
if __name__ == "__main__":
root=Tk()
c=Controller(root)
root.title("log")
root.geometry("750x500")
root.mainloop()

python 2.7 Tk change label to carry file name from opened file

I have this code in python 2.7 using tkinter that creates a Button on a Frame to open a file. There's a Label under it. I'm trying to make it so once the file is opened, the label prints the path, "file1.name" or whatever, on the Label, and if you open a new file it will change that Label again.
Also, I'm betting there's a better way to move data between the functions than I'm using here with global, but that's not worrying me right now.
I have to move the data from the opened files between functions so that I can mix the data and save to a new file. The code is:
from Tkinter import *
import Tkinter
import tkFileDialog
import tkMessageBox
root = Tkinter.Tk()
global rfile1
global rfile2
rfile1 = ""
rfile2 = ""
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.grid()
self.createWidgets1()
self.createLabels1()
self.createWidgets2()
self.createLabels2()
def createWidgets1(self):
self.oButton = Button(self, text = "open1", command = self.openfile1)
self.oButton.grid()
def createLabels1(self):
self.oLabel = Label(self, text = "whoops")
self.oLabel.grid()
def createWidgets2(self):
self.oButton = Button(self, text = "open2", command= self.openfile2)
self.oButton.grid()
def createLabels2(self):
self.oLabel2 = Label(self, text = "whoops2")
self.oLabel2.grid()
def openfile1(self):
file1 = tkFileDialog.askopenfile(title = "choose a file, *****", parent=root, mode = 'rb')
rfile1 = file1.read()
tkMessageBox.showinfo("oy", rfile1, parent=root)
def openfile2(self):
file2 = tkFileDialog.askopenfile(parent=root, mode='rb')
rfile2 = file2.read()
tkMessageBox.showinfo("hola", rfile2, parent=root)
app = Application()
app.master.title("whiggy whompus")
app.mainloop()
If I understand correctly, you want something like (untested):
def openfile1(self):
file1 = tkFileDialog.askopenfile(title = "choose a file, *****", parent=root, mode = 'rb')
self.oLabel.configure(text=file1.name)
rfile1 = file1.read()
tkMessageBox.showinfo("oy", rfile1, parent=root)
#mgilson has solved your first question. Your second question, about how to pass parameters between functions without using globals :
you might want to look at storing the variables as attributes on your application class :
The syntax self. is an attribute on the current instance (an instance being a particular example of a class - just like your car is a specific example of a class "car").
You can use instance attributes in this example as if they are globals.
from Tkinter import *
import Tkinter
import tkFileDialog
import tkMessageBox
root = Tkinter.Tk()
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.grid()
self.createWidgets1()
self.createLabels1()
self.createWidgets2()
self.createLabels2()
self.rfile1 = ""
self.rfile2 = ""
def createWidgets1(self):
self.oButton = Button(self, text = "open1", command = self.openfile1)
self.oButton.grid()
def createLabels1(self):
self.oLabel = Label(self, text = "whoops")
self.oLabel.grid()
def createWidgets2(self):
self.oButton = Button(self, text = "open2", command= self.openfile2)
self.oButton.grid()
def createLabels2(self):
self.oLabel2 = Label(self, text = "whoops2")
self.oLabel2.grid()
def openfile1(self):
file1 = tkFileDialog.askopenfile(title = "choose a file, *****", parent=root, mode = 'rb')
self.rfile1 = file1.read()
tkMessageBox.showinfo("oy", self.rfile1, parent=root)
def openfile2(self):
file2 = tkFileDialog.askopenfile(parent=root, mode='rb')
self.rfile2 = file2.read()
tkMessageBox.showinfo("hola", self.rfile2, parent=root)
app = Application()
app.master.title("whiggy whompus")
app.mainloop()

Categories

Resources