I wrote a CAD coordinate conversion application that reads a .txt file using filedialok.askopenfilename() using the function read_file_click().
After selecting the appropriate scale in the Combobox, the program converts the file using the convert() function, then saves it to a .txt file after calling the function save_file_click().
The problem is that when I send the returned value from the convert function to the save_file_click() function, I get two notifications about opening the file.
I don't know how to correct this error. I tried using global variables, but it doesn't help, and weak errors appears with the data_list_no_head variable. Thanks for help:)
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os
root = Tk()
root.title("Autocad Coordinate Converter")
root.geometry("")
root.geometry("280x320")
root.resizable(False, False)
def combo_sets():
scale_combo.set("")
def ending_message():
messagebox.showinfo("Autocad Coordinate Converter", "End")
def read_file_click():
global data_list_no_head
file_path = filedialog.askopenfilename()
return file_path
def convert():
file_path_new = read_file_click()
data_list = []
with open(file_path_new, encoding='utf-16') as file:
for line in file:
data_list.append(line.split())
data_list_no_head = data_list[4:]
return data_list_no_head
def save_file_click():
new = convert()
scale_get = scale_combo.get()
data = None
event_eng = None
cal = None
x_coordinate = None
y_coordinate = None
output_file = open(output_file_path_name, 'a')
if scale_get == "1:500" or scale_get == "1:1000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = int(event_eng[-1])*2-2
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
elif scale_get == "1:2000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = 2*(int(event_eng[-1])*2-2)
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
elif scale_get == "1:5000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = 5*(int(event_eng[-1])*2-2)
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
elif scale_get == "1:10000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = 20*(int(event_eng[-1])-2)
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
# Frame1
frame1 = LabelFrame(root, padx=15, pady=15, relief=FLAT)
frame1.grid(row=1, column=0)
button_1 = Button(frame1, text="Read .txt file", padx=15, pady=15, width=20, height=1, command=read_file_click)
button_1.grid(row=1, column=0, padx=3, pady=3)
# Frame2
frame2 = LabelFrame(root, padx=15, pady=15, relief=FLAT)
frame2.grid(row=2, column=0)
Label(frame2, text="Select scale:", width=14).grid(row=1, column=1, padx=1, pady=1)
scale_combo = ttk.Combobox(frame2, values=["1:500", "1:1000", "1:2000", "1:5000", "1:10000"], width=9, state='readonly')
scale_combo.current()
scale_combo.grid(row=2, column=1, padx=1, pady=1)
# Frame3
frame3 = LabelFrame(root, padx=50, pady=50, relief=FLAT)
frame3.grid(row=3, column=0)
button_2 = Button(frame3, text="Save file in CAD format", padx=15, pady=15, width=20, height=1,
command=save_file_click)
button_2.grid(row=0, column=0, padx=3, pady=3)
root.mainloop()
Related
I am new to Python and have a problem displaying serial data on my canvas in a tk GUI. I have set up the GUI and all is working, but the data is not displaying in the canvas.
I feel that I am missing something small...
Secondly, when I click the buttons to connect, the GUI freezes up.
Her is my code.
Any help would be welcome
Here is a picture of the current GUI
import serial
import serial.tools.list_ports
import tkinter as tk
from tkinter import *
from tkinter import ttk
import time
import time as tm
from configparser import ConfigParser
import os
import logging
current_time = tm.strftime('%H:%M:%S - %D')
#Get current ports and devices connected
ports = serial.tools.list_ports.comports()
serialInst = serial.Serial()
#List available ports
portlist = []
for onePort in ports:
portlist.append(str(onePort))
#Set logfile
def logfile():
os.system("notepad.exe " + config['Logger']['logfilename'])
# Read config file settings
config = ConfigParser()
config.read('config.ini')
#global logFileName
logFileName = config['Logger']['logfilename']
## Logger Configuration
def setupLogger(filename):
logger = logging.getLogger("Log")
logger.setLevel(config['Logger']['loglevel'])
# create file handler which logs even debug messages
fh = logging.FileHandler(filename)
fh.setLevel(config['Logger']['loglevel'])
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(config['Logger']['loglevel'])
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s ~ %(name)s ~ %(levelname)s ~ %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
# Return the Created logger
return logger
log = setupLogger(logFileName)
# Method to read config file settings
portsettings = config['serial_settings']
ser = serial.Serial(
port=config['serial_settings']['port'],
baudrate=config['serial_settings']['baudrate'],
parity=config['serial_settings']['parity'],
#stopbits=config['serial_settings']['stop bits']
)
def initPort():
while True:
if ser.in_waiting:
packet = ser.readline.decode('utf')
def connect():
ser.timeout = None
ser.writeTimeout = 0
tk.Label(dataFrame, text='Starting Up Serial Monitor').grid(row=1, column=1)
print("Starting Up Serial Monitor")
try:
ser.open()
except Exception as e:
log.info("Check if serial port is open.")
print("Check if serial port is open: " + str(e))
log.info(str(e))
if ser.isOpen():
try:
ser.flushInput()
ser.flushOutput()
ser.write((config['Commands']['maint']+'\n').encode('ascii'))
tk.Label(dataFrame, text="Serial data sent : " + config['Commands']['maint'], bg='white').grid(row=2, column=1)
ser.write((config['Commands']['inst']+'\n').encode('ascii'))
tk.Label(dataFrame, text="Serial data sent : " + config['Commands']['inst'], bg='white').grid(row=3, column=1)
ser.write((config['Commands']['dnl']+'\n').encode('ascii'))
tk.Label(dataFrame, text="Serial data sent : " + config['Commands']['dnl'], bg='white').grid(row=4, column=1)
ser.write((config['Commands']['status8']+'\n').encode('ascii'))
tk.Label(dataFrame, text="Serial data sent : " + config['Commands']['status8'], bg='white').grid(row=5, column=1)
log.info("Serial Data written to port.")
time.sleep(1)
numberOfLine = 0
while True:
response = ser.readline().decode('utf')
log.info("Reading serial data.")
log.info("Serial data read :"+response)
numberOfLine = numberOfLine + 1
Label(dataFrame, text=("Serial data read : " + response), bg='white').grid(row=7, column=1)
if numberOfLine >= 30:
break
ser.close()
except Exception as e:
print("Error communicating...: " + str(e))
else:
print("Cannot open serial port.")
log.error("Cannot open serial port.")
root = Tk()
root.resizable(True, True)
root.config(bg='light grey')
root.title(config['Info']['Application'] + config['Info']['ver'] + ' - Start Time ' + current_time)
copy_Label = Label(root, text=config['Info']['Copyright'], fg="red", font="Clibri 8 ").grid(column=1, row=50)
window_width = 600
window_height = 500
# get the screen dimension
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# find the center point
center_x = int(screen_width/2 - window_width / 2)
center_y = int(screen_height/2 - window_height / 2)
# set the position of the window to the center of the screen
root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
#Serial settings frame
sersetframe = Frame(root, highlightbackground="black", highlightthickness=2)
sersetframe.grid(row=1, column=1, padx=5, pady=5)
#Display serial settings from config
topLabel = Label(sersetframe, text='Serial Config Details. ', fg="black", bg='white', font="Clibri 10 bold").grid(row=2, column=1)
portLabel = Label(sersetframe, text='Port = '+config['serial_settings']['port'], fg="blue", bg='white', font="Clibri 10 bold").grid(row=3, column=1)
baudLabel = Label(sersetframe, text='Baudrate = '+config['serial_settings']['baudrate'], fg="blue", bg='white', font="Clibri 10 bold").grid(row=4, column=1)
paritytLabel = Label(sersetframe, text='Parity = '+config['serial_settings']['parity'], fg="blue", bg='white', font="Clibri 10 bold").grid(row=5, column=1)
#Button frame
buttonframe = Frame(root, highlightbackground="black", highlightthickness=2)
buttonframe.grid(row=49, column=2, padx=5, pady=5)
#Output frame
opframe = Frame(root, highlightbackground="black", highlightthickness=2)
opframelabel = Label(opframe, font='ariel 8 bold', bg='white', fg='blue', text='Serial Output')
opframelabel.grid(row=0, column=1)
opframe.grid(row=10, column=1, padx=5, pady=5)
#Output Canvas
dataCanvas = Canvas(root, width=350, height=200, bg='white')
dataCanvas.grid(row=30, column=1)
#Scrollbar
vsb = Scrollbar(root, orient='vertical', command=dataCanvas.yview)
vsb.grid(row=30, column=0, rowspan=10, sticky='ns')
dataCanvas.config(yscrollcommand=vsb.set)
dataFrame = Frame(dataCanvas, bg='white')
dataCanvas.create_window((10, 0), window=dataFrame, anchor='nw')
# Action Buttons
sendBtn = tk.Button(buttonframe, text='Send', command=connect).grid(column=1, row=7)
connectBtn = tk.Button(buttonframe, text='Connect', command=initPort).grid(column=1, row=8)
exitBtn = tk.Button(buttonframe, text='Exit', command=root.destroy).grid(column=1, row=9)
#Info frame
infoframe = Frame(root, highlightbackground="black", highlightthickness=2)
infoframelabel = Label(infoframe, font='ariel 8 bold', bg='white', fg='black', text='Info:')
infoframelabel.grid(row=0, column=1)
infoframe.grid(row=49, column=1, padx=5, pady=5)
# Check config file settings
dir_path = os.path.dirname(os.path.realpath(__file__))
config_filepath = dir_path+"\config.ini"
# check if the config file exists
exists = os.path.exists(config_filepath)
if exists:
print("**** config.ini file found at : ", config_filepath)
configfileLabel = Label(infoframe,text='Found config file at : '+config_filepath, fg="green",
bg='white', font="Clibri 10 bold").grid(row=49, column=1)
else:
print("**** config.ini file WAS NOT FOUND at : ", config_filepath)
configfileLabel = Label(root,text='DID NOT FIND config file at : ' + config_filepath, fg="red",
bg='white', font="Clibri 10 bold").grid(row=49, column=1)
comportLabel = Label(infoframe, text='Available COM ports : '+str(onePort), fg="black",
bg='white', font="Clibri 10 bold").grid(row=50, column=1)
#Run gui
root.mainloop()
Below is a small code where if you click add button a pop-up will appear where you write desired number. The number in the bottom represents the sum of all numbers you entered.
What I am trying to achieve is to update the sum_lbl and index_no as I delete any of the labels.
Code:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
Output:
After deleting the 3rd and 4th label the output is:
I would suggest to change area_lst to dictionary using the frame as the key and the two labels as the value for each row.
Then update destroy() to use area_lst to update the total and indexes:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = {} # dictionary to hold labels of each row using frame as the key
def destroy(frame):
frame.destroy()
del area_lst[frame]
update_total()
# update index of remaining rows
for idx, (lbl, _) in enumerate(area_lst.values(), 1):
lbl['text'] = idx
# function to update the total label
def update_total():
area_sum = sum(int(room['text']) for _, room in area_lst.values())
sum_lbl.config(text=area_sum)
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
def ok_():
name = add_room_area_var.get()
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=len(area_lst)+1)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
# store current row to area_lst
area_lst[entry_frame] = (index_lbl, add_room_lbl)
add_room_area.destroy()
update_total()
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
You can allow buttons to call multiple commands, so for your 'close_button' button, I added two more commands: remove the name from 'area_lst' and update the 'sum_lbl' text with the new sum for 'area_lst'
Like this:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:[destroy(entry_frame), area_lst.remove(int(name)), sum_lbl.config(text=sum(area_lst))])
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
I'm trying to do a Canvas that display a picture in a new window with a pressing a button, actually that is working, but I need the display that show the image in the new windows resize to the new window dimension.
I already tried to manage to get the size to an specific but nothing really worked out for me.
Here is the code:
from tkinter import *
import requests
import shutil
from xml.dom.minidom import parse
import fileinput
import os.path as path
import os
import tempfile
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
root = Tk()
root.title("Etiquetas")
root.configure(width=1280,height=720)
root.geometry('{}x{}'.format(427, 600))
root.resizable(width=False, height=False)
canvas = Canvas(root, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
def new_winF(): # new window definition
newwin = Toplevel(root)
display = Label(newwin, text="Humm, see a new window !")
display.pack()
def retrieve_input():
f = open('DataXML.xml', 'w+')
f.truncate(0)
inputParamString = ParamString.get("1.0","end-1c")
inputAlto = Alto.get("1.0","end-1c")
inputAncho = Ancho.get("1.0","end-1c")
inputTemplateLabel = TemplateLabel.get("1.0","end-1c")
#StringEtiqueta = open("DataXML.xml", "a+")
f.write(inputParamString)
f.close()
doc = parse("DataXML.xml")
my_node_list = doc.getElementsByTagName("label_param")
LabelResultado = open("Template.txt", "w")
LabelResultado.write(inputTemplateLabel)
LabelResultado.close()
for node in my_node_list:
name_node = node.getElementsByTagName("name")
value_node = node.getElementsByTagName("value")
y = ("[" + name_node[0].firstChild.data + "]")
z = y.upper()
print(z)
if (value_node[0].firstChild != None):
print(value_node[0].firstChild.data)
x = value_node[0].firstChild.data
else:
print("")
x = ""
with fileinput.FileInput("Template.txt", inplace=True) as file:
for line in file:
print(line.replace(z, x), end='')
w = open('Template.txt.bak', 'w+')
w.close()
codigoZPL = open("Template.txt", "r")
zpl = codigoZPL.read()
codigoZPL.close()
url = ('http://api.labelary.com/v1/printers/8dpmm/labels/'+inputAlto+'x'+inputAncho+'/0/')
files = {'file': zpl}
#headers = {'Accept': 'application/pdf'}
response = requests.post(url, headers=0, files=files, stream=True)
if response.status_code == 200:
response.raw.decode_content = True
with open('label.png', 'wb') as out_file: # change file name for PNG images
shutil.copyfileobj(response.raw, out_file)
else:
print('Error: ' + response.text)
newwin = Toplevel(root)
ncanvas = Canvas(newwin, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
display = canvas.create_image(850, 50, anchor=NE, image=my_image)
line = canvas.create_line(0, 0, 0, 0)
display.pack()
root.mainloop()
def click_limpiar():
Alto.delete(0.0, END)
Ancho.delete(0.0, END)
ParamString.delete(0.0, END)
TemplateLabel.delete(0.0, END)
def close_window():
root.destroy()
exit()
#Crear un label
Label (text="Ingresar ParamString: ") .place(x=10,y=15)
Label (text="Ingresar Tamaño (pulgadas): ") .place(x=10,y=160)
Label (text="Ingresar TemplateLabel: ") .place(x=10,y=218)
#Crear un textbox
ParamString = Text(root)
ParamString.pack()
ParamString.place(x=12, y=50, height=100, width=400)
Alto = Text(root)
Alto.pack()
Alto.place(x=12, y=190, height=20, width=20)
Ancho = Text(root)
Ancho.pack()
Ancho.place(x=52, y=190, height=20, width=20)
TemplateLabel = Text(root)
TemplateLabel.pack
TemplateLabel.place(x=12, y=250, height=300, width=400)
#Botones
Button(root, text="Aceptar", width=16, command=retrieve_input) .place(x=20,y=560)
Button(root, text="Limpiar", width=16, command=click_limpiar) .place(x=150,y=560)
Button(root, text="Salir", width=16, command=close_window) .place(x=280,y=560)
app = Window(root)
root.mainloop()
The Canvas part is this one:
newwin = Toplevel(root)
ncanvas = Canvas(newwin, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
display = canvas.create_image(850, 50, anchor=NE, image=my_image)
line = canvas.create_line(0, 0, 0, 0)
display.pack()
Thanks in advance,
I'm new with python and stack overflow so sorry if this question is below average. Anyway, I'm trying to make a Registration Software with python and tkinter, and I want to make it so that the buttons toggle between the purple colour: #ff4dd2. It is made hard because the buttons are created from a loop, I can't assign a variable to the buttons. If you could take the time to take a look at this it would be really appreciated :) (The current code works as expected, hopefully you can understand what I mean)
from tkinter import *
import time
import datetime
import re
root = Tk()
root.title("Attendence Register")
root.geometry('1350x650+0+0')
root.resizable(False, False)
nameframe = Frame(root, height=650, width=300)
nameframe.pack(side='left')
saveframe = Frame(root, height=650, width=300)
saveframe.pack(side='right')
outlist = []
def saveDataPresent(line):
present[line].configure(bg='#ff4dd2')
line = (line + ' is present')
outlist.append(line)
#print(outlist)
def saveDataAbsent(line):
absent[line].configure(bg='#ff4dd2')
line = (line + ' is absent')
outlist.append(line)
#print(outlist)
def saveDataIll(line):
ill[line].configure(bg='#ff4dd2')
line = (line + ' is ill')
outlist.append(line)
#print(outlist)
def saveDataHoliday(line):
holiday[line].configure(bg='#ff4dd2')
line = (line + ' is on holiday')
outlist.append(line)
#print(outlist)
def saveData():
now = datetime.datetime.now()
now = str(now)
dire = 'logs/'
now = dire + now
now = re.sub(':', '', now)
now += '.txt'
log = open(now, "w+")
log.close()
log = open(now, "a")
for i in outlist:
i = (i + '\n')
log.write(i)
log.close()
text = open('names.txt','r')
line = text.readline()
count = 0
present = {}
absent = {}
ill = {}
holiday = {}
for line in text:
count+= 1
name = Label(nameframe, text=line)
name.grid(row=count, column = 0)
present[line] = Button(nameframe, text='/', pady = 20, padx=20, bg ='#66ff66', command=lambda line=line: saveDataPresent(line))
present[line].grid(row=count, column = 2)
holiday[line] = Button(nameframe, text='H', pady=20, padx=20, bg='light blue', command=lambda line=line: saveDataHoliday(line))
holiday[line].grid(row=count, column=3)
ill[line] = Button(nameframe, text='ill', pady=20, padx=20, bg ='#ffa31a', command=lambda line=line: saveDataIll(line))
ill[line].grid(row=count, column=4)
absent[line] = Button(nameframe, text='NA', pady=20, padx=20, bg ='#ff6666', command=lambda line=line: saveDataAbsent(line))
absent[line].grid(row=count, column=5)
savebut = Button(saveframe, text='Save', pady = 20, padx=20, command=saveData)
savebut.pack()
root.mainloop()
I put this in the comments but it didnt look nice:
def saveDataHoliday(line):
holidaycount[line] += 1
if holidaycount[line] % 2 == 1:
holiday[line].configure(bg='#ff4dd2')
line = (line + ' is holiday')
outlist.append(line)
#print(outlist)
else:
holiday[line].configure(bg='light blue')
line = (line + ' is holiday')
outlist.remove(line)
#print(outlist)enter code here
holidaycount was defined earlier as a dictionary:
holidaycount = {}
I did this for each button(absent, present etc) Then after that:
for line in text:
count+= 1
name = Label(nameframe, text=line)
name.grid(row=count, column = 0)
presentcount[line] = 0
absentcount[line] = 0
illcount[line] = 0
holidaycount[line] = 0
I would like to add parallel actions in one button in tkinter window, this is my main code
from Fonctions import *
from time import time, sleep
listConnextion = [a,b,c,d,e,f]
MotDePasse= ""
class ConnecOptimizerApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
tk.Tk.iconbitmap(self , default= "logo.ico")
tk.Tk.wm_title(self,"ConnecOptimizer")
container = tk.Frame(self)
container.pack(side = "top", fill = "both", expand = True)
self.frames ={}
for f in (PageAccueil, PageAttente):
frame = f(container,self)
self.frames[f] = frame
frame.grid(row = 1000, column = 500, sticky = "nsew")
self.show_frame(PageAccueil)
def show_frame(self,cont):
frame = self.frames[cont]
frame.tkraise()
class PageAccueil(tk.Frame):
def __init__(self,parent,controller):
def cocher():
if var4 == 0:
ip.configure(state='disabled')
else:
ip.configure(state='normal')
tk.Frame.__init__(self,parent)
Frame0 = ttk.Frame(self)
Frame0.pack(side="top")
Frame1 = ttk.Frame(Frame0)
Frame1.pack(side="left", padx=70, pady=50)
Frame2 = ttk.Frame(Frame0)
Frame2.pack(side="left", padx=10, pady=10)
Frame3 = ttk.Frame(self)
Frame3.pack(side="top")
Frame4 = ttk.Frame(Frame3)
Frame4.pack(side = "left")
Frame5 = ttk.Frame(Frame3)
Frame5.pack(side = "left")
Fr = ttk.Frame(self).pack(side = "top")
Frame6 = ttk.Frame(self)
Frame6.pack(side = "top")
Frame7 = ttk.Frame(Frame6)
Frame7.pack(side="left")
Frame8 = ttk.Frame(Frame6)
Frame8.pack(side="left")
Frame9 = ttk.Frame(self)
Fr2 = ttk.Frame(self).pack(side = "top")
Frame9.pack(side = "top")
Frame10 = ttk.Frame(Frame9)
Frame10.pack(side = "left")
Frame11 = ttk.Frame(Frame9)
Frame11.pack(side = "left")
Frame12 = ttk.Frame(self)
Frame12.pack(side = "top")
varGr = tk.StringVar()
varGr.set(0)
for i in range(len(listConnextion)):
b = ttk.Radiobutton(Frame1, variable=varGr, text=listConnextion[i], value=i)
b.grid(row=i , sticky = "w")
var1 = tk.IntVar()
ttk.Checkbutton(Frame2, text="Graphique", variable=var1).grid(row=1 ,sticky = "w" )
var2 = tk.IntVar()
ttk.Checkbutton(Frame2, text="Diagnostic", variable=var2).grid(row=2 , sticky = "w")
var3 = tk.IntVar()
ttk.Checkbutton(Frame2, text="Optimisation", variable=var3).grid(row=3 , sticky = "w")
lab = ttk.Label(Frame4, text = "Periode de reference de l'historique en jour ")
lab.pack(side = "left" , padx = 30 )
nbJour = ttk.Entry(Frame5)
nbJour.pack(side = "left" )
l = ttk.Label(Fr).pack()
lab2 = ttk.Label(Frame7, text = "Nombre d'entrées pour finir l'apprentissage")
lab2.pack(side = "left" , padx = 30)
nbEntre = ttk.Entry(Frame8)
nbEntre.pack(side = "left" )
l2 = ttk.Label(Fr2).pack()
var4 = tk.IntVar()
ttk.Checkbutton(Frame10 , text = "Iperf", variable = var4 , command = cocher).pack( padx = 10)
ip = ttk.Entry(Frame11 , state = 'disabled')
ip.pack(padx = 20)
B = ttk.Button(Frame12, text="Valider" , command = (lambda: controller.show_frame(PageAttente)))
B.pack(side = "top" , pady = 30)
class PageAttente(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
frame0 = ttk.Frame(self)
frame0.pack(side = "top")
frame1 = ttk.Frame(self)
frame1.pack(side = "top")
self.T = tk.Text(frame0, height=20, width=53)
self.S = ttk.Scrollbar(frame0)
self.T.config(yscrollcommand=self.S.set)
self.T.pack(side=tk.LEFT, fill=tk.Y)
self.S.config(command=self.T.yview)
self.S.pack(side=tk.RIGHT, fill=tk.Y)
self.updateWidgets()
ttk.Button(frame1, text = "Arreter Diagnostic", command = (lambda : controller.show_frame(PageAccueil)) ).pack(pady = 10)
def updateWidgets(self):
with open('text.txt') as f:
newText = f.read()
self.T.delete('1.0', tk.END)
self.T.insert(tk.END, newText)
self.after(1000, self.updateWidgets)
app = ConnecOptimizerApp()
app.geometry("450x400+300+140")
app.mainloop()
and here you can find my fonctions
import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
def PageLogin():
root = tk.Tk()
root.geometry("350x130+530+280")
root.title("Super-utilisateur")
def leave():
MotDePasse = champMp.get()
print(MotDePasse)
root.destroy()
topFrame = ttk.Frame(root)
topFrame.pack()
middleFrame = ttk.Frame(root)
middleFrame.pack()
bottomFrame = ttk.Frame(root)
bottomFrame.pack()
lab1 = ttk.Label(topFrame, text=" ").pack()
lab2 = ttk.Label(topFrame, text="Veuillez entrer le mot de passe super-utilisateur").pack()
labelMessage2 = ttk.Label(middleFrame, text="mot de passe ")
labelMessage2.pack(side="left", padx=10, pady=10)
champMp = ttk.Entry(middleFrame, show='*')
champMp.pack(side="right", padx=10, pady=10)
b = ttk.Button(bottomFrame, text="valider", command = leave)
b.grid(row=4, pady=5, sticky="w")
root.mainloop()
def TracerGraphe ():
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
ax2 = fig.add_subplot(1, 1, 1)
ax3 = fig.add_subplot(1, 1, 1)
def animate(i):
graph_data = open('test.txt', 'r').read()
lines = graph_data.split('\n')
xs = []
ys = []
zs = []
ws = []
for line in lines:
if len(line) > 1:
x, y, z, w = line.split(',')
xs.append(x)
ys.append(y)
zs.append(z)
ws.append(w)
ax1.clear()
ax2.clear()
ax3.clear()
ax1.plot(xs, ys, label='RTT')
ax2.plot(xs, zs, label='Debit')
ax3.plot(xs, ws, label='taux d erreur')
ax1.legend()
ax2.legend()
ax3.legend()
ani = animation.FuncAnimation(fig, animate, interval=1000)
mngr = plt.get_current_fig_manager()
mngr.window.setGeometry(700, 100, 640, 545)
plt.show()
What I cant is : When I press the B button I want to show the PageAttente using "lambda: controller.show_frame(PageAttente)" , show the LoginPage using "PageLogin()" fonction and show the graph using "TracerGraphe ()"
I have tried all the solutions I found on net but it doesnt work
Can anyone help me please ?
Thanks