python) How do I make tkinter appear when a button is pressed? - python

# import library
import os
import csv
import pandas as pd
import librosa.display
import librosa
import numpy as np
from numpy.fft import fft
from scipy import signal
from scipy.sparse.linalg import svds
from scipy.linalg import hankel
from acoustics.cepstrum import complex_cepstrum
import matplotlib.pyplot as plt
from matplotlib import mlab
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# import GUI
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tksheet import Sheet
from tkinter import filedialog as fd
import tkinter.messagebox as msgbox
# input sr
sr = 2000
ts = 1/sr
style.use('ggplot')
**# tkinter**
main_win = tk.Tk()
main_win.title('program')
main_win.option_add('*font', ('Verdana', 15))
root = tk.Tk()
root.title('Mouse Event')
# mouse event
global mouse_click_no
global mouse_pos
mouse_pos = []
mouse_click_no = 0
mouse_data = []
frame = Frame(main_win)
frame.pack(pady=5)
label = Label(main_win)
label.pack()
# ----------------------------------------------------------------------------------------------------------------------
# csv viewer
def open_file():
global file_name
file_name = fd.askopenfilename(title="Open a File",
filetype=(("csv Files", "*.csv"), ("All Files", "*.*")),
initialdir=r'C:/Users/Ninebell/Desktop/test_data/')
if file_name:
try:
filename = r"{}".format(file_name)
df = pd.read_csv(filename)
except ValueError:
label.config(text="File could not be opened")
except FileNotFoundError:
label.config(text="File Not Found")
disp_csv()
# clear all the previous data in tree
clear_treeview()
tree.pack()
# add new data in treeview widget
tree["column"] = list(df.columns)
tree["show"] = "headings"
# for headings iterate over the columns
for col in tree["column"]:
tree.heading(col, text=col)
# put data in rows
df_rows = df.to_numpy().tolist()
for row in df_rows:
tree.insert("", "end", values=row)
def clear_treeview():
tree.delete(*tree.get_children())
tree = ttk.Treeview(frame)
# display csv file
class disp_csv(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
csv_title=file_name.split('/')[-1]
self.title(csv_title)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
self.frame = tk.Frame(self)
self.frame.grid_columnconfigure(0, weight=1)
self.frame.grid_rowconfigure(0, weight=1)
self.sheet = Sheet(
self.frame,
data=pd.read_csv(
file_name, # filepath here
).values.tolist(),
)
self.sheet.enable_bindings()
self.frame.grid(row=0, column=0, sticky="nswe")
self.sheet.grid(row=0, column=0, sticky="nswe")
# ----------------------------------------------------------------------------------------------------------------------
**# root tkinter**
def mouse_pos_update(rows):
global mouse_data
mouse_data = rows
treeview.delete(*treeview.get_children())
for i in rows:
treeview.insert('', 'end', values=i)
def save_button():
if len(treeview.get_children()) < 1:
msgbox.showerror('No Data', 'No data available to export')
return False
file_path = fd.asksaveasfilename(title='Save CSV',
filetypes=(("CSV File", "*.csv"), ("All files", "*.*")),
initialdir=r'C:/Users/Ninebell/Desktop/test_data/')
with open(file_path, mode='w', newline='') as myfile:
exp_writer = csv.writer(myfile, delimiter=',')
for i in treeview.get_children():
row = treeview.item(i)['values']
exp_writer.writerow(row)
msgbox.showinfo('Message', 'Export sucessfully')
def load_csv():
mouse_data.clear()
file_path = fd.askopenfilename(title='Open CSV',
filetypes=(("CSV File", "*.csv"), ("All files", "*.*")),
initialdir=r'C:/Users/Ninebell/Desktop/test_data/')
with open(file_path) as myfile:
csv_reader = csv.reader(myfile, delimiter=',')
for i in csv_reader:
mouse_data.append(i)
mouse_pos_update(mouse_data)
msgbox.showinfo('Data imported', 'Your data has be imported to' + os.path.basename(file_path) + 'sucessfully')
txt_browse['text'] = file_path
return None
def clear_button():
treeview.delete(*treeview.get_children())
for item in canvas.get_tk_widget().find_all():
canvas.get_tk_widget().delete(item)
def root_quit():
root.destroy()
# canvas.delete('all')
# ----------------------------------------------------------------------------------------------------------------------
# main_win GUI
menu = tk.Menu(main_win)
menu.config(font=('Verdana', 9))
comm_menu = tk.Menu(menu, tearoff=0)
file_menu = tk.Menu(menu, tearoff=0)
tbf_menu = tk.Menu(menu, tearoff=0)
freq_menu = tk.Menu(menu, tearoff=0)
over_menu = tk.Menu(menu, tearoff=0)
hanm_menu = tk.Menu(menu, tearoff=0)
spec_menu = tk.Menu(menu, tearoff=0)
stft_menu = tk.Menu(menu, tearoff=0)
wave_menu = tk.Menu(menu, tearoff=0)
psd_menu = tk.Menu(menu, tearoff=0)
mfcc_menu = tk.Menu(menu, tearoff=0)
stab_menu = tk.Menu(menu, tearoff=0)
ceps_menu = tk.Menu(menu, tearoff=0)
sine_menu = tk.Menu(menu, tearoff=0)
# telecommunications
comm_menu.add_command(label='Communication')
comm_menu.add_separator()
comm_menu.add_radiobutton(label='Sensor Connection')
comm_menu.add_radiobutton(label='Start')
comm_menu.add_radiobutton(label='Stop')
comm_menu.add_radiobutton(label='Save(csv)')
menu.add_cascade(label='Communication', menu=comm_menu)
# file menu
file_menu.add_command(label='Open File', command=open_file)
# file_menu.add_command(label='Read csv File', command=open_file) # csv 파일 읽기
file_menu.add_separator()
file_menu.add_command(label='Exit', command=quit)
menu.add_cascade(label='File', menu=file_menu)
# overall spectrum
over_menu.add_command(label='Overall Spectrum')
over_menu.add_separator()
over_menu.add_radiobutton(label='x-axis')
over_menu.add_radiobutton(label='y-axis')
over_menu.add_radiobutton(label='z-axis')
menu.add_cascade(label='Overall', menu=over_menu)
# time base frequency menu
tbf_menu.add_command(label='Time Domain', command=disp_time)
tbf_menu.add_separator()
tbf_menu.add_radiobutton(label='x-axis', command=x_time)
tbf_menu.add_radiobutton(label='y-axis', command=y_time)
tbf_menu.add_radiobutton(label='z-axis', command=z_time)
menu.add_cascade(label='Time', menu=tbf_menu)
# frequency menu
freq_menu.add_command(label='Frequency', command=disp_freq)
freq_menu.add_separator()
freq_menu.add_radiobutton(label='x-axis', command=x_freq)
freq_menu.add_radiobutton(label='y-axis', command=y_freq)
freq_menu.add_radiobutton(label='z-axis', command=z_freq)
menu.add_cascade(label='Freq', menu=freq_menu)
# spectrogram 2d
spec_menu.add_command(label='2D Plot', command=disp_spec2d)
spec_menu.add_separator()
spec_menu.add_radiobutton(label='x-axis', command=x_spec2d)
spec_menu.add_radiobutton(label='y-axis', command=y_spec2d)
spec_menu.add_radiobutton(label='z-axis', command=z_spec2d)
spec_menu.add_separator()
# spectrogram 3d
spec_menu.add_command(label='3D Plot', command=disp_spec3d)
spec_menu.add_separator()
spec_menu.add_radiobutton(label='x-axis', command=x_spec3d)
spec_menu.add_radiobutton(label='y-axis', command=y_spec3d)
spec_menu.add_radiobutton(label='z-axis', command=z_spec3d)
menu.add_cascade(label='Spectrogram', menu=spec_menu)
# cepstrum
ceps_menu.add_command(label='Cepstrum', command=disp_ceps)
ceps_menu.add_separator()
# cepstrum time
ceps_menu.add_radiobutton(label='Time x-axis', command=x_ceps)
ceps_menu.add_radiobutton(label='Time y-axis', command=y_ceps)
ceps_menu.add_radiobutton(label='Time z-axis', command=z_ceps)
ceps_menu.add_separator()
# cepstrum frequency
ceps_menu.add_radiobutton(label='Frequency x-axis')
ceps_menu.add_radiobutton(label='Frequency y-axis')
ceps_menu.add_radiobutton(label='Frequency z-axis')
menu.add_cascade(label='Cepstrum', menu=ceps_menu)
# hankel matrix
hanm_menu.add_command(label='Hankel Matrix', command=disp_hank)
hanm_menu.add_separator()
# hankel matrix time
hanm_menu.add_radiobutton(label='Time x-axis', command=x_hank_t)
hanm_menu.add_radiobutton(label='Time y-axis', command=y_hank_t)
hanm_menu.add_radiobutton(label='Time z-axis', command=z_hank_t)
hanm_menu.add_separator()
# hankel matrix frequency
hanm_menu.add_radiobutton(label='Frequency x-axis', command=x_hank_f)
hanm_menu.add_radiobutton(label='Frequency y-axis', command=y_hank_f)
hanm_menu.add_radiobutton(label='Frequency z-axis', command=z_hank_f)
hanm_menu.add_separator()
# hankel matrix spectrum
hanm_menu.add_radiobutton(label='Spectrum x-axis', command=x_hank_s)
hanm_menu.add_radiobutton(label='Spectrum y-axis', command=y_hank_s)
hanm_menu.add_radiobutton(label='Spectrum z-axis', command=z_hank_s)
menu.add_cascade(label='Hankel', menu=hanm_menu)
# wavelet
wave_menu.add_command(label='Wavelet', command=disp_wave)
wave_menu.add_separator()
wave_menu.add_radiobutton(label='x-axis', command=x_wave)
wave_menu.add_radiobutton(label='y-axis', command=y_wave)
wave_menu.add_radiobutton(label='z-axis', command=z_wave)
menu.add_cascade(label='Wavelet', menu=wave_menu)
# STFT
stft_menu.add_command(label='STFT', command=disp_stft)
stft_menu.add_separator()
stft_menu.add_radiobutton(label='x-axis', command=x_stft)
stft_menu.add_radiobutton(label='y-axis', command=y_stft)
stft_menu.add_radiobutton(label='z-axis', command=z_stft)
menu.add_cascade(label='STFT', menu=stft_menu)
# MFCC
mfcc_menu.add_command(label='MFCC', command=disp_mfcc)
mfcc_menu.add_separator()
mfcc_menu.add_radiobutton(label='x-axis', command=x_mfcc)
mfcc_menu.add_radiobutton(label='y-axis', command=y_mfcc)
mfcc_menu.add_radiobutton(label='z-axis', command=z_mfcc)
menu.add_cascade(label='MFCC', menu=mfcc_menu)
# PSD
psd_menu.add_command(label='PSD', command=disp_psd)
psd_menu.add_separator()
psd_menu.add_radiobutton(label='x-axis', command=x_psd)
psd_menu.add_radiobutton(label='y-axis', command=y_psd)
psd_menu.add_radiobutton(label='z-axis', command=z_psd)
menu.add_cascade(label='PSD', menu=psd_menu)
# sine test
sine_menu.add_command(label='Sine Test', command=disp_sine)
sine_menu.add_separator()
sine_menu.add_radiobutton(label='x-axis', command=x_sine)
sine_menu.add_radiobutton(label='y-axis', command=y_sine)
sine_menu.add_radiobutton(label='z-axis', command=z_sine)
menu.add_cascade(label='Sine Test', menu=sine_menu)
# stability
stab_menu.add_command(label='Stability')
stab_menu.add_separator()
stab_menu.add_radiobutton(label='x-axis')
stab_menu.add_radiobutton(label='y-axis')
stab_menu.add_radiobutton(label='z-axis')
menu.add_cascade(label='Stability', menu=stab_menu)
# ----------------------------------------------------------------------------------------------------------------------
# root GUI
frame = Frame(root)
frame.pack(fill='x', padx=5, pady=5)
treeview = tk.ttk.Treeview(frame,
columns=['one', 'two', 'three'],
displaycolumns=['one', 'two', 'three'],
show='headings',
height=10)
treeview.pack(fill='both', padx=5, pady=5)
treeview.column('#1', width=150, anchor='center')
treeview.heading('one', text='index', anchor='center')
treeview.column('#2', width=150, anchor='center')
treeview.heading('two', text='Frequency[Hz]', anchor='center')
treeview.column('#3', width=150, anchor='center')
treeview.heading('three', text='Amplitude[mV/g]', anchor='center')
# browse
browse_frame = LabelFrame(root, text='Open File Dialog')
browse_frame.pack(fill='both', padx=5, pady=5)
txt_browse = Label(browse_frame, text='No File Selected', font=('Verdana', 9, 'bold'))
txt_browse.pack(fill='x', padx=5, pady=5)
# button
button_frame = Frame(root) # bg='white'
button_frame.pack(fill='x', padx=5, pady=5)
btn_exit = Button(button_frame, text='Exit', width=12, command=root_quit)
btn_exit.pack(side='right', padx=5, pady=5)
btn_del = Button(button_frame, text='Clear', width=12, command=clear_button)
btn_del.pack(side='right', padx=5, pady=5)
btn_save = Button(button_frame, text='Save', width=12, command=save_button)
btn_save.pack(side='right', padx=5, pady=5)
btn_load = Button(button_frame, text='Load', width=12, command=load_csv)
btn_load.pack(side='right', padx=5, pady=5)
# ----------------------------------------------------------------------------------------------------------------------
# GUI
root.config(menu=menu)
main_win.config(menu=menu)
main_win.geometry('800x500')
main_win.resizable(False, False)
main_win.mainloop()
This code is a program that displays a graph for each signal when a file is selected. Among them, FFT is set to display the coordinate values in the tree view when the mouse button is pressed. But I want the FFT screen to appear when the button is pressed, but I don't know how to do that part. Should I dig a new class and rewrite it?

for background image in tkinter
from tkinter import *
canv = Canvas(width=200, height=200)
image = PhotoImage(file="./logo.png")
canv.create_image(100, 100, image=image)
canv.grid(row=0, column=1)

Related

Upload txt file to draw xy graph python

my name is Vo Minh Hoang. I wrote a Python program to upload file to draw graph but i have one problem which is the button to draw graph. Please help me and thank you very much. I send an image which is an example I want to complete the program.
from tkinter import *
from tkinter import filedialog
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
# functions
def openFile():
tf = filedialog.askopenfilename(
initialdir="C:/Users/MainFrame/Desktop/",
title="Open Text file",
filetypes=(("Text Files", "*.txt"),)
)
pathh.insert(END, tf)
tf = open(tf)
file_cont = tf.read()
txtarea.insert(END, file_cont)
tf.close()
def Draw():
tf = plt.figure(
mode='w',
title ="Draw",
ax = plt.subplots()
plt.subplots_adjust(left=0.3, bottom=0.25)
X, Y = np.loadtxt('data.txt', delimiter=',', unpack=True)
p, = ax.plot(X, Y, color="blue", marker="o")
print(X, Y)
)
tf.config(mode='w')
pathh.insert(END, tf)
data = str(txtarea.get(1.0, END))
tf.write(data)
tf.close()
ws = Tk()
ws.title("PythonGuides")
ws.geometry("400x500")
ws['bg']='#2a636e'
# adding frame
frame = Frame(ws)
frame.pack(pady=20)
# adding scrollbars
ver_sb = Scrollbar(frame, orient=VERTICAL )
ver_sb.pack(side=RIGHT, fill=BOTH)
hor_sb = Scrollbar(frame, orient=HORIZONTAL)
hor_sb.pack(side=BOTTOM, fill=BOTH)
# adding writing space
txtarea = Text(frame, width=40, height=20)
txtarea.pack(side=LEFT)
# binding scrollbar with text area
txtarea.config(yscrollcommand=ver_sb.set)
ver_sb.config(command=txtarea.yview)
txtarea.config(xscrollcommand=hor_sb.set)
hor_sb.config(command=txtarea.xview)
# adding path showing box
pathh = Entry(ws)
pathh.pack(expand=True, fill=X, padx=10)
# adding buttons
Button(
ws,
text="Open File",
command=openFile
).pack(side=LEFT, expand=True, fill=X, padx=20)
Button(
ws,
text="Draw",
command=Draw
).pack(side=LEFT, expand=True, fill=X, padx=20)
Button(
ws,
text="Exit",
command=lambda:ws.destroy()
).pack(side=LEFT, expand=True, fill=X, padx=20, pady=20)
ws.mainloop()
This is the code I try to complete
I tried to find in the Internet but it didn't work.
enter image description here

How can I return a variable from a function that is opening a file using filedialog after selecting a tkinter button?

All of the tutorials I have seen deomonstrate the tkinter filedialog.askopenfilename function by only using the information collected within the function that is linked to the tkinter button. I can pass information in the function, but I would like to pass variables (filepath, images, etc.) outside the function and have them update variables in my GUI.
I have commented out the location I would like to call the variables in main_gui_setup function below. Any help will be appreciated, as it has been very demoralizing not being able to open a file. If this problem persists, my future as a programmer may be limited to creating tic-tac-toe games or instructional videos for Youtube.
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog, messagebox
from PIL import ImageTk, Image # was import PIL.Image, PIL.ImageTk
import cv2
def main():
root = Tk()
window1 = Window(root, "X-ray Assist", "Give up")
return None
# can't pass by reference in python
class Window():
n = 0
file_path = ""
img1_info = ""
def __init__(self, root, title, message):
self.root = root
self.root.title(title)
#self.root.geometry(geometry)
self.screen_width = root.winfo_screenwidth()
self.screen_height = root.winfo_screenheight()
#self.root.attributes('-topmost', 1)
# SET APP WINDOW SIZE
scr_size_main = self.scr_size() # create instance of scr_size
self.root.geometry("%dx%d+%d+%d" % (self.root_width, self.root_height, self.root_x, self.root_y))
# CREATE MAIN WINDOW GUI
create_gui = self.main_gui_setup()
self.root.mainloop()
pass
def scr_size(self):
'''Reads monitor size and adjusts GUI frame sizes'''
self.root_width = int(self.screen_width*0.52)
self.root_height = int(self.screen_height*0.9)
self.root_x = int(self.screen_width*0.23)
self.root_y = int(self.screen_height*0.02)
self.img_ht_full = int(self.screen_height*0.82)
self.tools_nb_width = int(self.screen_width*0.22)
self.tools_nb_height = int(self.screen_height*0.48)
self.hist_nb_width = int(self.screen_width*0.22)
self.hist_nb_height = int(self.screen_height*0.23)
def open_image(self):
main_win = ttk.Frame(self.root)
main_win.grid(column=0, row=0)
self.file_path = filedialog.askopenfilename(initialdir='/', title='Open File',
filetypes=(('tif files', '*.tif'), ('all files', '*.*')))
self.file_path_label = ttk.Label(main_win, text=self.file_path)
self.file_path_label.grid(column=0, row=0, columnspan=1, sticky="nw", padx=(5,0), pady=1)
self.img1_8bit = cv2.imread(self.file_path, 0) #, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_GRAYSCALE)
#self.img1_8bit_resize = cv2.resize(self.img1_8bit, (self.img_ht_full, self.img_ht_full)) #, interpolation = cv2.INTER_CUBIC)
#self.img1_height, self.img1_width = self.img1_8bit.shape # not resized for screen
#img1_info = text = f"{self.img1_height} {self.img1_8bit.dtype} {self.img1_16bit.dtype}"
#print(self.img1_width, " x ", self.img1_height, " bitdepth = ", self.img1_8bit.dtype)
#img1_info = ttk.Label
#print(f"{self.img1_height} {self.img1_width} {self.img1_8bit.dtype}")
#img1_info.grid(column=3, row=1, columnspan=1, sticky="w", padx=(5,0), pady=1)
#img = io.imread(main_win.filename) #scikit
self.img1_16bit = cv2.imread(self.file_path, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_GRAYSCALE)
#self.img_canvas = tk.Canvas(self.root, width=self.img_ht_full, height=self.img_ht_full)
#self.img_canvas.grid(column=1, row=2, columnspan=10, rowspan=10, sticky="nw")
#self.img_canvas.image = ImageTk.PhotoImage(image=Image.fromarray(self.img1_8bit_resize))
#self.img_canvas.create_image(0,0, image=self.img_canvas.image, anchor="nw")
# .create_line(x1, y1, x2, y2, fill="color")
#self.img_canvas.create_line((self.img_ht_full/2), 0, (self.img_ht_full/2), (self.img_ht_full), fill="yellow")
#self.img_canvas.create_line(0, (self.img_ht_full/2), (self.img_ht_full), (self.img_ht_full/2), fill="yellow")
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.grid(column=0, row=0)
image_win = ttk.Frame(main_win, borderwidth=25, relief="groove", width=self.img_ht_full, height=self.img_ht_full)
image_win.grid(column=1, row=2, columnspan=10, rowspan=10, sticky="nw")
toolbar = ttk.Frame(main_win, borderwidth=5) #, width=1100, height=15)
toolbar.grid(column=0, row=0, columnspan=10, rowspan=1, sticky="nw", padx=20)
hist_win = ttk.Frame(main_win, borderwidth=25, relief="groove", width=300, height=200)
panel_info = ttk.Label(main_win, text=f"{self.screen_width} x {self.screen_height}")
panel_info.grid(column=5, row=1, columnspan=1, sticky="e", pady=1)
# SCROLL SLIDER AT BOTTOM
slider = ttk.Scrollbar(main_win, orient="horizontal")
slider.grid(column=1, row=13, columnspan=7, padx=5, pady=5, sticky="ew")
#X-RAY AND DETECTOR SETTINGS - will input these from separate class
kv = ttk.Label(main_win, text="125kV")
kv.grid(column=0, row=2, columnspan=1, padx=15, pady=5)
file_path_label = ttk.Label(main_win, text="No image loaded")
file_path_label.grid(column=1, row=1, columnspan=1, sticky="nw", padx=(5,0), pady=1)
# CREATE BUTTONS
open = ttk.Button(toolbar, text="Open", width=10, command=self.open_image)
open.grid(column=0, row=0)
save = ttk.Button(toolbar, text="Save", width=10)
save.grid(column=1, row=0)
b1 = ttk.Button(toolbar, text="1", width=10)
b1.grid(column=2, row=0)
b2 = ttk.Button(toolbar, text="2", width=10)
b2.grid(column=3, row=0)
pass
main()
You aren't thinking of event driven programming correctly. In event driven programming you have callbacks to the functions you defined. Let's look at your code:
def get_path(self):
...
self.path_label = ...
...
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.pack()
open = ttk.Button(main_win, text="Open", width=10, command=self.get_path)
open.pack()
# Problematic code:
# main_label = ttk.Label(main_win, self.path_label)
# main_label.pack()
When main_gui_setup is called it creates a frame and a button inside it. When the button is clicked it calls get_path which sets up the path_label variable. The problem that you were facing is that that as soon as you create your button (without waiting for the button to be pressed), you create the label called main_label.
For a simple fix to your problem try this:
def get_path(self):
...
self.file_path = ...
self.path_label = ...
...
def button_callback(self, main_win):
# set up
self.get_path()
# My guess is that you wanted `self.file_path` here instead of `self.path_label`
main_label = ttk.Label(main_win, self.file_path)
main_label.pack()
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.pack()
# I am using a lambda and passing in `main_win` because you haven't
# assigned it to `self` using `self.main_win = ...`
open = ttk.Button(main_win, text="Open", width=10, command=lambda: self.button_callback(main_win))
open.pack()
I am still confused by what You are trying to accomplish:
from tkinter import Tk, Button, Label, filedialog
class MainWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.open_file_btn = Button(self, text='Open', command=self.open_file)
self.open_file_btn.pack()
self.file_name = None
def open_file(self):
self.file_name = filedialog.askopenfilename()
Label(self, text=self.file_name).pack()
root = MainWindow()
root.mainloop()
I will explain what will happen here! (You can change the .askopenfilename() attributes obviously).
When the program opens the filedialog and You select a file, that file name will now get assigned to self.file_name and that variable can be used anywhere in the class.
also from what I have seen You should learn more about classes and PEP 8

Filter display of Tkinter Treeview using a function

I have a Tkinter Treeview, which I import .csv data into. I then manually assign Not Started Yet To Arrive to the row of columnn Current Status via an .option menu drop down. What is the best way to create a function to filter the treeview and only show rows with Not Started in the Current Status column? I have so far explored options using the following doc. Trying .detach but I dont think this appropriate for my application. https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/ttk-Treeview.html
import tkinter as tk
from tkinter import *
import tkinter.ttk as tkrttk
from PIL import Image, ImageFont, ImageTk
import csv
from tkinter import filedialog
root = tk.Tk()
button_1 = Button(root, text="Not Started", command = "SomeFunction")
button_1.place(x=0, y=0, height=50, width=150)
treetime = tkrttk.Treeview(root)
treetime['columns'] = ("Column2", "Column3", "Column4", "Column5",
"Column6", "Column7", "Column8", "Column9", "Column10", "Column11")
column_list = list(treetime ['columns'])
treetime.place(x=0, y=60)
treetime.column("#0", width=0)
treetime.column("Column2", width=80, minwidth=50)
treetime.column("Column3", width=80, minwidth=50)
treetime.column("Column4", width=80, minwidth=50)
treetime.column("Column5", width=80, minwidth=50)
treetime.column("Column6", width=80, minwidth=100)
treetime.column("Column7", width=300, minwidth=100)
treetime.column("Column8", width=200, minwidth=100)
treetime.column("Column9", width=200, minwidth=100)
treetime.column("Column10", width=300, minwidth=100)
treetime.column("Column11", width=200, minwidth=100)
treetime.heading('#0', text="", anchor=tk.W)
treetime.heading('Column2', text="Ro Number", anchor=tk.W)
treetime.heading('Column3', text="Date In", anchor=tk.W)
treetime.heading('Column4', text="Time In", anchor=tk.W)
treetime.heading('Column5', text="Time Out", anchor=tk.W)
treetime.heading('Column6', text="Rego Number", anchor=tk.W)
treetime.heading('Column7', text="Customer Name", anchor=tk.W)
treetime.heading('Column8', text="Vehicle Make", anchor=tk.W)
treetime.heading('Column9', text="Vehicle Model", anchor=tk.W)
treetime.heading('Column10', text="Job Description", anchor=tk.W)
treetime.heading('Column11', text="Current Status", anchor=tk.W)
def select_input_file():
global input_file_path
input_file_path = filedialog.askopenfilename(
filetypes=(("CSV files", "*.csv"),))
with open(input_file_path) as csv_file:
rdr = csv.DictReader(csv_file)
for row in rdr:
RoNumber = row['Ro Number']
DateIn = row['Date In']
TimeIn = row['Time In']
TimeOut = row['Time Out']
RegoNumber = row['Rego Number']
CustomerName = row['Customer Name']
VehicleMake = row['Vehicle Make']
VehicleModel = row['Vehicle Model']
JobDescription = row['Job Description']
CurrentStatus = row['Current Status']
treetime.insert("", 0, values=(RoNumber, DateIn, TimeIn, TimeOut, RegoNumber,
CustomerName, VehicleMake, VehicleModel, JobDescription, CurrentStatus))
StatusList = [
"Not Started",
"Yet to Arrive",
]
Status = StringVar()
Status.set(0)
def set_status(value):
row = treetime.focus()
treetime.set(row, 'Column11', value)
def set_status(value):
row = treetime.focus()
if row:
treetime.set(row, 'Column11', value)
drop=tkrttk.OptionMenu(root, Status, "Select Status", *StatusList, command=set_status)
drop.place(x=1440, y=0, height=50, width=150)
drop=tkrttk.OptionMenu(root, Status, "Select Status", *StatusList, command=set_status)
drop.place(x=1440, y=0, height=50, width=150)
root.mainloop()

Need to Add a Scroll Toolbar to FGCs LabelFrame (Tkinter)

Working on an internal app and trying to get a scrollbar to "FGCs" labelFrame only, in addition, I need to scale the frame to the app size.
I'll be happy if anyone could assist me in refactoring this and create the scrollbar.
I know that I need to create a canvas or something, but do not know how.
This is a first time for me with Tkinter.
from tkinter import *
import os, subprocess
from tkinter import ttk
managment = ["MAIN","NAV","OUTPUT","OUTPUTSPARE","GATEWAY","Sync1","Sync2"]
servers = ["recon01","recon02","recon03","recon04","recon05","recon06","recon07","recon08","recon09","recon10","recon11","recon12","render01","render02","storinator"]
FGCs =["fgc01","fgc02","fgc03","fgc04","fgc05","fgc06","fgc07","fgc08","fgc09","fgc10","fgc11","fgc12","fgc13","fgc14","fgc15","fgc16","fgc17","fgc18","fgc19","fgc20","fgc21","fgc22","fgc23","fgc24","fgc25","fgc26","fgc27","fgc28","fgc29","fgc30","fgc31","fgc32","fgc33","fgc34","fgc35","fgc36","fgc37","fgc38","fgcspare1","fgcspare2","fgcspare3","fgcspare4"]
tests = ["Network", "GPU", "Time", "Gidel", "Snapshot", "Disks"]
testbuttons = []
serverbuttons = []
managebuttons = []
fgcbuttons = []
class mainwindow:
global test
global testbuttons
global managment
global managebuttons
global FGCs
def __init__(self,master):
self.master = master
master.title("System Report Tool")
master.geometry("1000x500")
self.Tests = ttk.LabelFrame(root, text="Tests")
self.Tests.pack(expand="no",anchor=W,pady=20)
for test in tests:
testcheck = ttk.Checkbutton(self.Tests, text=test)
testcheck.pack(side=LEFT, anchor="n")
testbuttons.append(testcheck)
def select_tests():
for test in testbuttons:
test.invoke()
selecttests = ttk.Checkbutton(root, text="Select All",command=select_tests)
selecttests.place(x=260,y=16)
self.Managment = ttk.LabelFrame(root, text="Managment")
self.Managment.configure(width=10, height=20)
self.Managment.pack(expand="no",anchor=W)
for manage in managment:
managecheck = ttk.Checkbutton(self.Managment, text=manage)
managecheck.pack(side=TOP, anchor="w")
managebuttons.append(managecheck)
def select_manage():
for manage in managebuttons:
manage.invoke()
selectmanage = ttk.Checkbutton(self.Managment, text="Select All",command=select_manage)
selectmanage.pack()
self.FGCs = ttk.LabelFrame(root, text="FGCs")
self.FGCs.configure(width=10, height=20)
self.FGCs.place(x=120,y=80)
for fgc in FGCs:
fgccheck = ttk.Checkbutton(self.FGCs, text=fgc)
fgccheck.pack(side=TOP, anchor="w")
fgcbuttons.append(fgccheck)
def select_fgc():
for fgc in fgcbuttons:
fgc.invoke()
selectfgc = ttk.Checkbutton(self.FGCs, text="Select All",command=select_fgc)
selectfgc.pack()
root = Tk()
Window = mainwindow(root)
root.mainloop()
Thanks in advance.
Copy code with class ScrolledFrame from scrolled-frame-canvas
Create ScrolledFrame inside LabelFrame self.FGCs
self.sf = ScrolledFrame(self.FGCs)
self.sf.pack()
And then put widgets in inner element in ScrolledFrame instead of putting them in self.FGCs like
fgccheck = ttk.Checkbutton(self.sf.inner, text=fgc)
Working code
import os
import subprocess
import tkinter as tk
from tkinter import *
from tkinter import ttk
class ScrolledFrame(tk.Frame):
def __init__(self, parent, vertical=True, horizontal=False):
super().__init__(parent)
# canvas for inner frame
self._canvas = tk.Canvas(self)
self._canvas.grid(row=0, column=0, sticky='news') # changed
# create right scrollbar and connect to canvas Y
self._vertical_bar = tk.Scrollbar(self, orient='vertical', command=self._canvas.yview)
if vertical:
self._vertical_bar.grid(row=0, column=1, sticky='ns')
self._canvas.configure(yscrollcommand=self._vertical_bar.set)
# create bottom scrollbar and connect to canvas X
self._horizontal_bar = tk.Scrollbar(self, orient='horizontal', command=self._canvas.xview)
if horizontal:
self._horizontal_bar.grid(row=1, column=0, sticky='we')
self._canvas.configure(xscrollcommand=self._horizontal_bar.set)
# inner frame for widgets
self.inner = tk.Frame(self._canvas)
self._window = self._canvas.create_window((0, 0), window=self.inner, anchor='nw')
# autoresize inner frame
self.columnconfigure(0, weight=1) # changed
self.rowconfigure(0, weight=1) # changed
# resize when configure changed
self.inner.bind('<Configure>', self.resize)
# resize inner frame to canvas size
self.resize_width = False
self.resize_height = False
self._canvas.bind('<Configure>', self.inner_resize)
def resize(self, event=None):
self._canvas.configure(scrollregion=self._canvas.bbox('all'))
def inner_resize(self, event):
# resize inner frame to canvas size
if self.resize_width:
self._canvas.itemconfig(self._window, width=event.width)
if self.resize_height:
self._canvas.itemconfig(self._window, height=event.height)
managment = ["MAIN","NAV","OUTPUT","OUTPUTSPARE","GATEWAY","Sync1","Sync2"]
servers = ["recon01","recon02","recon03","recon04","recon05","recon06","recon07","recon08","recon09","recon10","recon11","recon12","render01","render02","storinator"]
FGCs =["fgc01","fgc02","fgc03","fgc04","fgc05","fgc06","fgc07","fgc08","fgc09","fgc10","fgc11","fgc12","fgc13","fgc14","fgc15","fgc16","fgc17","fgc18","fgc19","fgc20","fgc21","fgc22","fgc23","fgc24","fgc25","fgc26","fgc27","fgc28","fgc29","fgc30","fgc31","fgc32","fgc33","fgc34","fgc35","fgc36","fgc37","fgc38","fgcspare1","fgcspare2","fgcspare3","fgcspare4"]
tests = ["Network", "GPU", "Time", "Gidel", "Snapshot", "Disks"]
testbuttons = []
serverbuttons = []
managebuttons = []
fgcbuttons = []
class mainwindow:
global test
global testbuttons
global managment
global managebuttons
global FGCs
def __init__(self,master):
self.master = master
master.title("System Report Tool")
master.geometry("1000x500")
self.Tests = ttk.LabelFrame(root, text="Tests")
self.Tests.pack(expand="no", anchor=W, pady=20)
for test in tests:
testcheck = ttk.Checkbutton(self.Tests, text=test)
testcheck.pack(side=LEFT, anchor="n")
testbuttons.append(testcheck)
def select_tests():
for test in testbuttons:
test.invoke()
selecttests = ttk.Checkbutton(root, text="Select All",command=select_tests)
selecttests.place(x=260,y=16)
self.Managment = ttk.LabelFrame(root, text="Managment")
self.Managment.configure(width=10, height=20)
self.Managment.pack(expand="no",anchor=W)
for manage in managment:
managecheck = ttk.Checkbutton(self.Managment, text=manage)
managecheck.pack(side=TOP, anchor="w")
managebuttons.append(managecheck)
def select_manage():
for manage in managebuttons:
manage.invoke()
selectmanage = ttk.Checkbutton(self.Managment, text="Select All",command=select_manage)
selectmanage.pack()
self.FGCs = ttk.LabelFrame(root, text="FGCs")
self.FGCs.configure(width=10, height=20)
self.FGCs.place(x=120, y=80)
self.sf = ScrolledFrame(self.FGCs)
self.sf.pack()
for fgc in FGCs:
fgccheck = ttk.Checkbutton(self.sf.inner, text=fgc)
fgccheck.pack(side=TOP, anchor="w")
fgcbuttons.append(fgccheck)
def select_fgc():
for fgc in fgcbuttons:
fgc.invoke()
selectfgc = ttk.Checkbutton(self.sf.inner, text="Select All",command=select_fgc)
selectfgc.pack()
root = Tk()
Window = mainwindow(root)
root.mainloop()
EDIT: This code uses pack() with some options to resize widgets when window is resized
import os
import subprocess
import tkinter as tk
from tkinter import *
from tkinter import ttk
class ScrolledFrame(tk.Frame):
def __init__(self, parent, vertical=True, horizontal=False):
super().__init__(parent)
# canvas for inner frame
self._canvas = tk.Canvas(self)
self._canvas.grid(row=0, column=0, sticky='news') # changed
# create right scrollbar and connect to canvas Y
self._vertical_bar = tk.Scrollbar(self, orient='vertical', command=self._canvas.yview)
if vertical:
self._vertical_bar.grid(row=0, column=1, sticky='ns')
self._canvas.configure(yscrollcommand=self._vertical_bar.set)
# create bottom scrollbar and connect to canvas X
self._horizontal_bar = tk.Scrollbar(self, orient='horizontal', command=self._canvas.xview)
if horizontal:
self._horizontal_bar.grid(row=1, column=0, sticky='we')
self._canvas.configure(xscrollcommand=self._horizontal_bar.set)
# inner frame for widgets
self.inner = tk.Frame(self._canvas)
self._window = self._canvas.create_window((0, 0), window=self.inner, anchor='nw')
# autoresize inner frame
self.columnconfigure(0, weight=1) # changed
self.rowconfigure(0, weight=1) # changed
# resize when configure changed
self.inner.bind('<Configure>', self.resize)
# resize inner frame to canvas size
self.resize_width = False
self.resize_height = False
self._canvas.bind('<Configure>', self.inner_resize)
def resize(self, event=None):
self._canvas.configure(scrollregion=self._canvas.bbox('all'))
def inner_resize(self, event):
# resize inner frame to canvas size
if self.resize_width:
self._canvas.itemconfig(self._window, width=event.width)
if self.resize_height:
self._canvas.itemconfig(self._window, height=event.height)
managment = ["MAIN","NAV","OUTPUT","OUTPUTSPARE","GATEWAY","Sync1","Sync2"]
servers = ["recon01","recon02","recon03","recon04","recon05","recon06","recon07","recon08","recon09","recon10","recon11","recon12","render01","render02","storinator"]
FGCs =["fgc01","fgc02","fgc03","fgc04","fgc05","fgc06","fgc07","fgc08","fgc09","fgc10","fgc11","fgc12","fgc13","fgc14","fgc15","fgc16","fgc17","fgc18","fgc19","fgc20","fgc21","fgc22","fgc23","fgc24","fgc25","fgc26","fgc27","fgc28","fgc29","fgc30","fgc31","fgc32","fgc33","fgc34","fgc35","fgc36","fgc37","fgc38","fgcspare1","fgcspare2","fgcspare3","fgcspare4"]
tests = ["Network", "GPU", "Time", "Gidel", "Snapshot", "Disks"]
testbuttons = []
serverbuttons = []
managebuttons = []
fgcbuttons = []
class mainwindow:
global test
global testbuttons
global managment
global managebuttons
global FGCs
def __init__(self,master):
self.master = master
master.title("System Report Tool")
master.geometry("1000x500")
# --- top ---
self.Tests = ttk.LabelFrame(root, text="Tests")
self.Tests.pack(anchor='w', pady=20)
for test in tests:
testcheck = ttk.Checkbutton(self.Tests, text=test)
testcheck.pack(side='left', anchor="n")
testbuttons.append(testcheck)
def select_tests():
for test in testbuttons:
test.invoke()
selecttests = ttk.Checkbutton(root, text="Select All",command=select_tests)
selecttests.place(x=260,y=16)
# --- middle ---
self.Managment = ttk.LabelFrame(root, text="Managment")
self.Managment.configure(width=10, height=20)
self.Managment.pack(anchor='nw', side='left')
for manage in managment:
managecheck = ttk.Checkbutton(self.Managment, text=manage)
managecheck.pack(anchor="w")
managebuttons.append(managecheck)
def select_manage():
for manage in managebuttons:
manage.invoke()
selectmanage = ttk.Checkbutton(self.Managment, text="Select All",command=select_manage)
selectmanage.pack()
self.FGCs = ttk.LabelFrame(root, text="FGCs")
self.FGCs.configure(width=10, height=20)
self.FGCs.pack(fill='y', expand=True, side='left', anchor='w')
self.sf = ScrolledFrame(self.FGCs)
self.sf.pack(fill='y', expand=True)
for fgc in FGCs:
fgccheck = ttk.Checkbutton(self.sf.inner, text=fgc)
fgccheck.pack(anchor="w")
fgcbuttons.append(fgccheck)
def select_fgc():
for fgc in fgcbuttons:
fgc.invoke()
selectfgc = ttk.Checkbutton(self.sf.inner, text="Select All", command=select_fgc)
selectfgc.pack()
root = Tk()
Window = mainwindow(root)
root.mainloop()

How to print through local or network printer in tkinter

I want to select one of installed printer on my computer and print through it but my combobox doesn't display the printers on my machine but rather print to my terminal in my IDE .
Have been trying this for days with arriving at the solution to do this.Have installed the win32print module to after reading about it.This my code below:
from tkinter import *
from tkinter import ttk
import win32print
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,
textvariable=installed_printer).pack()
BUTTON = ttk.Button(pt, text="refresh",
command=installed_printer).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10)
def INFO():
print(T2.get("1.0", END))
Print_Button = Button(root, text ="Print", command =
INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()
How can i achieve this as i want to print the content in my Text box with tkinter framework.
Is this what you wanted to create?
from tkinter import *
from tkinter import ttk
import win32api
import win32print
import tempfile
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
printerdef = ''
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
var1 = StringVar()
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,textvariable=var1)
print_list = []
printers = list(win32print.EnumPrinters(2))
for i in printers:
print_list.append(i[2])
print(print_list)
# Put printers in combobox
PRCOMBO['values'] = print_list
PRCOMBO.pack()
def select():
global printerdef
printerdef = PRCOMBO.get()
pt.destroy()
BUTTON = ttk.Button(pt, text="Done",command=select).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10, wrap=WORD)
def INFO():
printText = T2.get("1.0", END)
print(printText)
print(printerdef)
filename = tempfile.mktemp(".txt")
open(filename, "w").write(printText)
# Bellow is call to print text from T2 textbox
win32api.ShellExecute(
0,
"printto",
filename,
'"%s"' % win32print.GetDefaultPrinter(),
".",
0
)
Print_Button = Button(root, text ="Print", command=INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()

Categories