Fetching a value of each Radiobutton group from n number of Radiobuttons - python

So i have a scenario when 'n' number of Independent radio groups have to be created and we shall be able to retreive value of each radio group independently.
Current code gives me the value of the last radio group irrespective of the button I press.
import tkinter # note that module name has changed from Tkinter in Python 2 to tkinter in Python 3
from tkinter import *
from tkinter import messagebox
top = tkinter.Tk()
top.title("NA")
a = int(input("Enter the number of frames"))
btn = [""]*a
def commd():
print(i)
print("Value changed to new value", values[i],'with value', values[i].get())
#print('Update in value')
values = [tkinter.IntVar() for i in range(len(btn))]
print(len(values))
for i in range(len(btn)):
print(i)
txt = "Button_Number", (i+1)
rtxt1 = 'Radio Button1',i+1
rtxt2 = 'Radio Button2',i+1
abc = Button(top, text = txt, activebackground = "Green", fg = "Blue", bg = "Red", height =5, command = aa)
R1 = Radiobutton(top, text = "START", activebackground = "Green", fg = "Blue", bg = "Red", height = 2,variable = values[i],value=0,command = commd)
R2 = Radiobutton(top, text = "STOP", activebackground = "Green", fg = "Blue", bg = "Red", height = 2,variable = values[i],value=1,command = commd)
abc.grid(row = i+i, column = 0,rowspan = 2)
R1.grid(row = i+i, column = 1)
R2.grid(row = i+i+1,column = 1)
mainloop()

Use .bind(... instead of command=... ...
Output:
Radio Button1.0 START
Radio Button2.1 STOP
Radio Button1.2 START
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("NA")
for i in range(3):
print(i)
variable = tk.StringVar()
for n, text in enumerate(('START', 'STOP'), 1):
r = tk.Radiobutton(self, text=text, value=text, variable=variable)
r.bind('<ButtonRelease-1>', self.on_click)
r._group = f'Radio Button{n}.{i}'
r._variable = variable
r.grid(row=i, column=n)
def on_click(self, event):
_ = self
w = event.widget
print(w._group, w._variable.get())
if __name__ == '__main__':
App().mainloop()

Related

how to access the output from clicking the recommendation button?

i am making a movie recommendation GUI with the help of a dataset. For that, i need the value selected from the list by clickng on the recommedation button but i am not able to figure out to do so.
from tkinter import *
import pandas as pd
window = Tk()
window.config(background = 'white')
window.geometry('700x500')
title = Label(text = 'Movie Recommendation', font = ('times new roman',20),background = 'white')
title.pack()
label = Label(text = '**********************', font = ('times new roman',17),background = 'white' )
label.pack()
label = Label(text = 'Movie List :', font = ('times new roman',17),background = 'white' )
label.place(x = 5, y =66)
scroll_bar = Scrollbar(window)
scroll_bar.pack(side = RIGHT, fill = Y)
list = Listbox(window, yscrollcommand = scroll_bar.set, height = 21, width = 40, background = 'white', foreground = 'black' )
for i in df['title']:
list.insert(END,i)
list.place(x=5,y=105)
rec = Label(text = 'Recommended Movies :', font = ('times new roman',17),background = 'white')
rec.place(x = 300, y = 66)
def selected_item():
print(list.get(ANCHOR))
# selected = Label(text = selected_item(),font = ('times new roman',15))
# selected.place(x=300,y = 96)
def movie():
button = Button(text = "Recommendation",foreground='black', command = selected_item,background = 'white')
button.place(x=5,y=460)
movie()
window.mainloop()
this is my code.
i tried everything i could think of but i am new to coding. thank you.

How do I proceed with the rest of the function to keep updating my message box in tkinter?

I am trying to do a message box to warns the user in my UI that they will be moved to the homepage after 10 seconds, codes are as following:
from tkinter import *
import warnings
import random
import time
import sqlite3
from tkinter import simpledialog
from tkinter import messagebox
from tkcalendar import *
from tkinter import ttk
import math
from PIL import Image, ImageTk
import winsound
##-------------Frames setup--------------------------
class VendingApp(Tk):
def __init__(self):
Tk.__init__(self)
self._frame = None
self.switch_frame(Home)
def switch_frame(self, frame_class):
#Destroys current frame and replaces it with a new one.
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
####-----------------------Home page---------------------------
class Home(Frame):
def __init__(self, master):
Frame.__init__(self, master)
##-----------------------fuctions-----------------------------------
def clicked(a):
if (a.x <=1920) and (a.y<=1080):
master.switch_frame(Store)
print ("1")
else:
None
None
##----------------setup------------------------------------------
self._images = list()
img_banner = Image.open("pic/banner.jpg")
img_banner = img_banner.resize((400,100), Image.ANTIALIAS)
banner = ImageTk.PhotoImage(img_banner)
self._images.append(banner)
##---------------------Top frame Home------------------------------------
topFrame = Frame(self,width = 1920, height = 1080)
topFrame.pack()
canvasM = Canvas(topFrame,height=1080, width=1920)
canvasM['highlightthickness'] = 0
canvasM.pack()
body = canvasM.create_rectangle(0, 0,1920,1080, fill = 'gray95')
mylabel = canvasM.create_text((960, 390),font=("Purisa", 40), text="Touch anywhere to continue")
canvasM.tag_bind(body,"<Button>",clicked)
canvasM.tag_bind(mylabel,"<Button>",clicked)
#-------------------------Store page--------------------------------------------------------------
class Store(Frame):
def __init__(self, master):
Frame.__init__(self, master)
def timeset():
global time
time = 15
def active(event):
global time
time = 15
print (time)
def timeout():
global time
if time >= 10:
time -= 1
master.after(1000, timeout)
elif time <= 10 and time > 0:
askuser()
time -= 1
master.after(1000, timeout)
elif time <= 0:
master.switch_frame(Home)
print(time)
def askuser():
ask = messagebox.showinfo('Are you there?','Returning to home page in ' + (str(time)) + ' seconds. \n please touch the screen to continue using the app')
self._images = list()
img_banner = Image.open("pic/banner.jpg")
img_banner = img_banner.resize((400, 100), Image.ANTIALIAS)
banner = ImageTk.PhotoImage(img_banner)
self._images.append(banner)
##---------------------pictures and filters Store------------------------------------
PicFrame = Frame(self, width=400, height=100)
PicFrame.grid(row = 0, column = 0)
PicFrame.grid_propagate(False)
canvas_for_banner = Canvas(PicFrame, height=100, width=400 ) # banner image
canvas_for_banner.pack(anchor = N)
canvas_for_banner['highlightthickness'] = 0
canvas_for_banner.grid_propagate(False)
canvas_for_banner.create_image(0, 0, anchor=NW, image=banner)
##---------------------------------Midd store-------------------
FilterFrame =Frame(self, width=400, height=930, relief = RAISED, bd =1)
FilterFrame.grid(row = 1, column = 0)
FilterFrame.pack_propagate(0)
Ava_title = Label(FilterFrame, text = "Availability", font = ('Helvetica', 20, 'bold'))
Ava_title.pack(pady = (100,0))
self.stock_yes = IntVar()
self.stock_no = IntVar()
check_ava = Checkbutton(FilterFrame, text = 'Avaliable', variable = self.stock_yes, font = 20, command = None)
check_ava.pack( anchor = 'w', padx = 30, pady =10)
check_unava = Checkbutton(FilterFrame, text = 'Unavaliable', font = 20, variable = self.stock_no, command = None)
check_unava.pack(anchor = 'w', padx = 30, pady = 10)
gend_title = Label(FilterFrame, text = "Gender", font = ('Helvetica', 20, 'bold'))
gend_title.pack(pady = (30,0))
self.boi = IntVar()
self.girl = IntVar()
check_boi = Checkbutton(FilterFrame, text = 'Male', font = 20, variable = self.boi)
check_boi.pack( anchor = 'w', padx = 30, pady = 10)
cehck_girl = Checkbutton(FilterFrame, text = 'Female', font = 20, variable = self.girl)
cehck_girl.pack(anchor = 'w', padx = 30, pady =10)
Class_title = Label(FilterFrame, text = "Uniform class", font = ('Helvetica', 20, 'bold'))
Class_title.pack(pady = (30,0))
self.formal = IntVar()
self.sport = IntVar()
check_formal = Checkbutton(FilterFrame, text = 'Formal', font = 20, variable = self.formal)
check_formal.pack( anchor = 'w', padx = 30, pady =10)
check_sport = Checkbutton(FilterFrame, text = 'Sport', font = 20, variable = self.sport)
check_sport.pack(anchor = 'w', padx = 30, pady =10)
type_title = Label(FilterFrame, text = "Type", font = ('Helvetica', 20, 'bold'))
type_title.pack(pady = (30,0))
self.shirts = IntVar()
self.pants = IntVar()
self.misc = IntVar()
check_shirts = Checkbutton(FilterFrame, text = 'Shirts', font = 20, variable = self.shirts)
check_shirts.pack( anchor = 'w', padx = 30, pady =10)
check_pants = Checkbutton(FilterFrame, text = 'Pants', font = 20, variable = self.pants)
check_pants.pack(anchor = 'w', padx = 30, pady =10)
check_misc = Checkbutton(FilterFrame, text = 'Misc', font = 20, variable = self.misc)
check_misc.pack(anchor = 'w', padx = 30, pady =10)
##------------------------\\\\\\\\\\\\\\\\\\\\\\---------------------------------------------
MidFrame = Frame(self,width = 1520, height = 1030, relief = SUNKEN, bd = 2)
MidFrame.grid(row = 0, column = 1, rowspan = 2)
MidFrame.grid_propagate(False)
store_canvas = Canvas(MidFrame, width = 1520, height = 1030)
store_canvas.pack()
store_canvas.pack_propagate(0)
frames = []
frame_order = []
num = 1
for x in range(4):
frames.append([])
for y in range(4):
frames[x].append(0)
for x in range(4):
for y in range(4):
frames[x][y] = Frame(store_canvas, width=1520 / 4, height=1030 / 4, bd = 2, relief = SOLID)
frames[x][y].grid(row=y, column=x)
frames[x][y].pack_propagate(False)
frame_order.append(frames[x][y])
for frame in frame_order:
Label(frame, text=num, anchor='nw').pack( side = 'left')
num += 1
##------------------------\\\\\\\\\\\\\\\\\\\\\\---------------------------------------------
BottomFrame = Frame(self,width = 1920, height = 50, bd = 2, relief = RAISED)
BottomFrame.grid(row = 2, column =0, columnspan = 2)
BottomFrame.pack_propagate(False)
help_btn = Button(BottomFrame, width = 5, height = 3, text = '?', image = None)
help_btn.pack(side = 'right')
master.bind("<Button>",active)
timeset()
timeout()
#----------------------------------------------------------------------------------------
if __name__ == "__main__":
root = VendingApp()
#Renames the TITLE of the window
root.title("Vending machine")
root.geometry("1920x1080")
root.attributes('-fullscreen', True)
root.resizable(False, False)
root.mainloop()
The problem is that the whole program 'freezes' every time the msg box pop up and unless the user confirms 'ok' then the function will pick up where it left off. Is there any way to keep the function going, hence the number in the msg box will update according to the time remaining? Am I approaching this problem the wrong way? Is there another module for this all along and I am just using the wrong module for the task? Please go easy on me, I am still learning. All responses all much appreciated.
messagebox will pause the further execution until it receives an input. To prevent this you can try the following
Use threading
from tkinter import *
from tkinter import messagebox
from threading import Thread
def msgbox():
def _display():
messagebox.showinfo('Info','Self distruction after 2 seconds')
Thread(target=_display).start()
root.after(2000,root.destroy)
root=Tk()
button=Button(root,text='Run',command=msgbox)
button.pack()
root.mainloop()
Create your own info box using Toplevel (the below example will create a replica (sort of) of standard windows info box)
from tkinter import *
import tkinter.ttk as ttk
class InfoBox(Toplevel):
def __init__(self,title,message,parent=None):
Toplevel.__init__(self,parent)
self.bell()
self.transient(self.master)
self.title(title)
self.config(bg='white')
top_frame=Frame(self,bd=0,bg=self['bg'])
top_frame.pack(side='top',fill='x',pady=20)
bottom_frame=Frame(self,bd=0)
bottom_frame.pack(side='bottom',fill='x')
self.info_icon=Canvas(top_frame,width=36,height=36
,bg=self['bg'],bd=0,highlightthickness=0)
self.info_icon.create_oval(0,0,30,30,fill='#0077be',outline='#0077be')
self.info_icon.create_text(15,16,text='i',font=('',18),fill='white')
self.info_icon.pack(side='left',padx=(20,0),anchor='center')
self.label=Label(top_frame,text=message,bg=self['bg'])
self.label.pack(padx=(1,20),pady=5,anchor='center')
self.ok_button=ttk.Button(bottom_frame,text='OK',
state='active',command=self.destroy)
self.ok_button.pack(anchor='e',padx=15,pady=10)
self.update()
center_x=self.winfo_screenwidth()//2-self.winfo_width()//2
center_y=self.winfo_screenheight()//2-self.winfo_height()//2
self.geometry(f'+{center_x}+{center_y}')
def msgbox():
InfoBox('Info','Self distruction after 2 seconds')
root.after(2000,root.destroy)
root=Tk()
button=Button(root,text='Run',command=msgbox)
button.pack()
root.mainloop()
UPDATE
Stacking is automatically prevented
from tkinter import *
import tkinter.ttk as ttk
class InfoBox(Toplevel):
def __init__(self):
self.exists=False
def call(self,title,message,parent=None):
if self.exists:
self._destroy()
Toplevel.__init__(self,parent)
self.bell()
self.transient(self.master)
self.title(title)
self.config(bg='white')
top_frame=Frame(self,bd=0,bg=self['bg'])
top_frame.pack(side='top',fill='x',pady=20)
bottom_frame=Frame(self,bd=0)
bottom_frame.pack(side='bottom',fill='x')
self.info_icon=Canvas(top_frame,width=36,height=36
,bg=self['bg'],bd=0,highlightthickness=0)
self.info_icon.create_oval(0,0,30,30,fill='#0077be',outline='#0077be')
self.info_icon.create_text(15,16,text='i',font=('',18),fill='white')
self.info_icon.pack(side='left',padx=(20,0),anchor='center')
self.label=Label(top_frame,text=message,bg=self['bg'])
self.label.pack(padx=(1,20),pady=5,anchor='center')
self.ok_button=ttk.Button(bottom_frame,text='OK',
state='active',command=self._destroy)
self.ok_button.pack(anchor='e',padx=15,pady=10)
self.update()
center_x=self.winfo_screenwidth()//2-self.winfo_width()//2
center_y=self.winfo_screenheight()//2-self.winfo_height()//2
self.geometry(f'+{center_x}+{center_y}')
self.protocol('WM_DELETE_WINDOW',self._destroy)
self.exists=True
def _destroy(self):
self.destroy()
self.exists=False
root=Tk()
infobox=InfoBox()
button=Button(root,text='Hello',command=lambda:infobox.call('Info','Hello'))
button.pack()
button1=Button(root,text='World',command=lambda:infobox.call('Info','World'))
button1.pack()
root.mainloop()

Stuck in while loop in GUI

I'm building a GUI that first accepts an input number from user and makes the corresponding button green. Now I run another python script that scans an apriltag(sort of QR Code) and returns an ID and writes it into a file placed in same folder. The code I've attached includes print statement at various point("Done", "phew","haha"). On running the GUI the command Done is printed first, followed by phew and haha(multiple times). However the button does not change its colour to green, it only changes its colour when the apriltag is detected by the camera. The code is attached. The function is called when I press the OK button in my GUI.
I have tried to include delays and also tried to use threading. But none of these methods worked.
import Tkinter
def action3():
f = open("test.txt","r")
data = f.read()
y = int(str(data))
f.close()
f = open("test.txt","w")
f.write("0")
f.close()
x = int(e.get())
f = open("test.txt","r")
data = f.read()
y = int(str(data))
f.close()
print("Done")
if (x == 1):
b1['bg'] = 'green'
b2['bg'] = 'white'
b3['bg'] = 'white'
b4['bg'] = 'white'
print("phew")
#time.sleep(2)
elif (x == 2):
b1['bg'] = 'white'
b2['bg'] = 'green'
b3['bg'] = 'white'
b4['bg'] = 'white'
print("phew")
elif (x == 3):
b1['bg'] = 'white'
b2['bg'] = 'white'
b3['bg'] = 'green'
b4['bg'] = 'white'
print("phew")
elif (x == 4):
b1['bg'] = 'white'
b2['bg'] = 'white'
b3['bg'] = 'white'
b4['bg'] = 'green'
print("phew")
#time.sleep(5)
while(y==0): ##Update y
f = open("test.txt","r")
data = f.read()
y=int(str(data))
print("Haha")
f.close()
time.sleep(2)
##Code for GUI
b1 = Button(window, text="Box1", bg='white', width=30, height=13)
b1.grid(row=1, sticky=W)
b2 = Button(window, text="Box2", bg = 'white', width = 30,height = 13)
b2.grid(row=2, sticky=W)
b3 = Button(window, text="Box3", bg = 'white', width = 30,height = 13)
b3.grid(row=1, column=1, sticky=W)
b4 = Button(window, text="Box4", bg = 'white', width = 30,height = 13)
b4.grid(row=2, column=1, sticky=W)
bget = Button(window, text="OK", bg='pink', width = 10,height =
2,command=action3)
bget.grid(row=3, column=0, sticky=E)
e = Entry(window)
e.grid(row=3, column=1)
window.mainloop()

Is it possible to grab a label variable and put into list with tkinter

I've created a temperature converter programme in which the calculated temperature from an entry widget gets displayed in a separate label, what I need to do is to grab that converted variable and put it into a list.
I think that making a connected entry widget to the label widget would work where they are connected so I could grab the variable using the .get method but that would look awfully messy. Is there any other way I could proceed with this?
This is my first post and I am a beginner in Python, very sorry if the code looks messy and if I included too much code.
data = []
tempVal = "Celcius"
def store_temp(sel_temp):
global tempVal
tempVal = sel_temp
class Calculator:
def __init__(self, num_a, num_b):
self.num_a= num_a
self.num_b = num_b
def convert(self):
if tempVal == 'Fahrenheit':
return float((float(self.num_a) - 32)* 5 / 9)
if tempVal == 'Celcius':
return float((float(self.num_a) * 9/ 5) + 32)
def display_add(entry_numa,entry_numb,label_answer):
#get the value from entry_numa
num_a = entry_numa.get()
num_b = entry_numb.get()
num_a = str(num_a)
num_b = str(num_b)
#create an object
global data
calc = Calculator(num_a,num_b)
label_answer['text'] = calc.convert()
data += [calc]
def calc_history():
global data
#creat e another window
window_calc_list = Tk()
window_calc_list.geometry("400x200")
#create a listbox
listbox_calc_list = Listbox(window_calc_list, width= 300)
listbox_calc_list.pack()
listbox_calc_list.insert(END, "list of data")
for info in data:
listbox_calc_list.insert(END, str(info.num_a) + " " + str(info.num_b) + " " )
window_calc_list.mainloop()
def main():
window = Tk()
window.geometry("500x150")
validate_letter = window.register(only_letters)
validate_nb = window.register(only_numbers_max_3)
label = Label(window, width = 30, background = 'lightblue', text='enter temperature, only numbers')
label.grid(row=0, column=0)
entry_numa = Entry(window, width = 30, validate="key", validatecommand=(validate_nb, '%d', '%P'))
entry_numa.grid(row = 0, column = 1)
#create another label and entry object for num_b
label_numb = Label(window, width = 30, background = 'lightblue', text='enter location, only letters')
label_numb.grid(row=1, column=0)
entry_numb = Entry(window, width = 30, validate="key", validatecommand=(validate_letter, '%d', '%S'))
entry_numb.grid(row = 1, column = 1)
#create another label to display answer
label_answer = Label(window, width = 30, background = 'lightyellow')
label_answer.grid(row = 2, column = 1)
entry_answer = Entry(window, width = 30)
entry_answer.grid(row = 2, column = 0)
button_add = Button(window, text = "ADD", command = lambda: display_add(entry_numa,entry_numb,label_answer))
button_add.grid(row=3, column = 0)
button_delete = Button(window, text = "DELETE", command = lambda: delete_data(data))
button_delete.grid(row=3, column = 2)
#create another button to display all previous calculations
button_display = Button(window,text = "calc_history", command = lambda: calc_history())
button_display.grid(row=3, column = 1)
var = StringVar()
dropDownList = ["Celcius", "Fahrenheit"]
dropdown = OptionMenu(window, var,dropDownList[0], *dropDownList, command=store_temp)
dropdown.grid(row=0, column=2)
window.mainloop()
A tk.Label displayed value can be accessed via the text property
, labelwidgetname['text'].
Depeneding on when and how you want the independent list of stored values
to be updated there are a variety of options. The example shows one if the
user is required to press a submission button. This could be adapted,
for example,when the tempreture calculation is performed.
Of course it would be simpler to update the list of stored values directly at the point in the script where the calculated tempreture for the label text has been derived.
import tkinter as tk
stored_values = []
def add_labelvalue_tolist(temp):
'''Store label value to list.'''
stored_values.append(temp)
print('contents of list', stored_values)
def add_entry_tolabel(event):
display_label['text'] = user_entry.get()
ROOT = tk.Tk()
user_entry = tk.Entry()
user_entry.grid(column=0, row=0)
user_entry.bind('<KeyRelease>', add_entry_tolabel)
display_label = tk.Label()
display_label.grid(column=1, row=0)
# update list via button command linked to label text value
add_button = \
tk.Button(text='add to list',
command=lambda:add_labelvalue_tolist(display_label['text']))
add_button.grid(column=0, row=1)
ROOT.mainloop()
try making a function that is like this
def letterused():
converter=(letter.get())# letter is a entry box at the bottom is the code
converted.set(converter)
for i in range(1):
used_letters1.append(converter) #list
letter = ttk.Entry(root, width = 20,textvariable = letter)
letter.pack()

Can't write full text in an Entry - tkinter

I'm working on a GUI software with Tkinter which basically print a general plane of the product after pushing the "Crear" button, as you can see at the following images:
GUI Interface
After pushing "Crear" Button
As you may have appreciated, once you give the full information at the entries and push the "Crear" button, a dynamic table (made with labels and entries in a for cycle) appear with the dimensions of the modules seen at the "Esquema" frame. The problem I have is that, when I edit the information at the dynamic table, I have an immediate change on the graph (which is possible thanks to the trace method) without letting me finish the number I'm already writing; I mean: I can't write the full number at the entries on the dynamic table before it make the changes on the graph. So, my question is: which function or command can I apply to make the program stop and reactivate after I finish writing the full number at the entries on the table?
Any help will be highly appreciated,
PS: I have already tried the "time.stop" and "after" functions. The first one crashed the program, which is unacceptable, and the second one increased the waiting time before I could continue writing numbers at the table. The full code of the program is really extensive, but here I share a runnable code:
Code
from tkinter import *
from tkinter import filedialog as fd
from tkinter import messagebox as ms
from tkinter import ttk
from io import open
import tkinter as tk
from pathlib import Path
import PIL
from PIL import Image, ImageTk
import glob
import sys
import numpy as np
import os
import os, os.path
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import time
#Made by:
#Juan David Argüello Plata
#----------------------------------------------CLASSES AND FUNCTIONS-----------------------------------------------------
class Interface():
def __init__(self, inter, w=860,h=700, titulo = "Example", titulo_principal = "EXAMPLE"):
inter.title(titulo)
inter.resizable(False, False)
#Dimensions of the screen
ws = inter.winfo_screenwidth()
hs = inter.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
#Position of the interface
inter.geometry('%dx%d+%d+%d' % (w, h, x, y))
titulo = Label(inter, text = titulo_principal, font=(fuente,24, "bold italic"))
titulo.pack()
self.inter = inter
#---Frames, labels and general data---
self.Principal_frames()
self.subframes()
self.Data()
#---Actions to execute---
Action(self)
def Principal_frames(self):
self.Frame_Table = Frame(self.inter)
self.Frame_Table.config(width = "400", height = "600", bd = 2, relief = "groove")
self.Frame_Table.place(x=10, y=50)
titulo = Label(self.Frame_Table, text = "Data", font=(fuente,20, "bold italic"))
titulo.place(x=180, y=5)
self.Frame_graph = Frame(self.inter)
self.Frame_graph.config(width = "400", height = "600", bd = 2, relief = "groove")
self.Frame_graph.place(x=450, y=50)
titulo = Label(self.Frame_graph, text = "Graph", font=(fuente,20, "bold italic"))
titulo.place(x=150, y=5)
def subframes(self):
self.subframe_Data = Frame(self.Frame_Table)
self.subframe_Data.config(width = "300", height = "200", bd = 2, relief = "groove")
self.subframe_Data.place(x=80, y=50)
self.subframe_graph = Frame(self.Frame_graph)
self.subframe_graph.config(width = "395", height = "400", bd = 2, relief = "flat")
self.subframe_graph.place(x=0, y=50)
def Data(self):
Length = Label(self.subframe_Data, text = "Length", font = Font)
Length.grid(row=0, column = 0, sticky=W, padx=3)
self.Length=Entry(self.subframe_Data, width=8)
self.Length.grid(row=0,column=1, sticky=W, padx=3)
self.Sub_Length=Entry(self.subframe_Data, width=8)
self.Sub_Length.grid(row=0,column=2, sticky=W, padx=3)
Width = Label(self.subframe_Data, text = "Width", font = Font)
Width.grid(row=1, column = 0, sticky=W, padx=3)
self.Width=Entry(self.subframe_Data, width=8)
self.Width.grid(row=1,column=1, sticky=W, padx=3)
self.Sub_Width=Entry(self.subframe_Data, width=8)
self.Sub_Width.grid(row=1,column=2, sticky=W, padx=3)
class Action(Interface):
def __init__(self, inter):
self.Interface = inter
self.modification = 0
Create = Button(self.Interface.subframe_Data, text="Create", font = Font, command = self.Table)
Create.grid(row=1,column=3)
def Table(self):
self.Table = Frame(self.Interface.Frame_Table)
self.Table.config(width = "150", height = "400", bd=2, relief="groove")
self.Table.place(x=80, y=150)
#Dimensions of the labels and entries of the table
Length = 176
Width = 200
#Reading of Data
self.Data = np.zeros(4)
self.Data[0] = float(self.Interface.Length.get())
self.Data[1] = float(self.Interface.Sub_Length.get())
self.Data[2] = float(self.Interface.Width.get())
self.Data[3] = float(self.Interface.Sub_Width.get())
#---Dynamic table ---
if self.Data[1] > self.Data[3]:
self.Max = self.Data[1]
else:
self.Max = self.Data[3]
#-Variables-
label = "label"
Entry_length = "length"
Entry_width = "width"
Numbers_label = [""]*(int(self.Max)+1)
self.width_data = [""]*(int(self.Max)+1)
self.length_data=[""]*(int(self.Max)+1)
self.First_Time = 0 #Counter that depends of the size of the table (help the program to recognize if it's the first time the "Create" button is pressed)
self.Modules = np.zeros((int(self.Max),2)) #Matrix which contains the table info
#--Scorllbar--
self.canvas_table = Canvas(self.Table)
self.canvas_table.pack(side="left", fill="both", expand = True)
self.canvas_table.config(width=str(Width), height=str(Length))
self.Frame_table = Frame(self.canvas_table)
self.Frame_table.config(width=str(Width), height=str(Length), relief="flat")
self.canvas_table.create_window(0,0,window= self.Frame_table, anchor = 'nw')
self.yscroll = Scrollbar(self.Table, orient = "vertical", command = self.canvas_table.yview)
self.yscroll.pack(side='right', fill='y')
self.canvas_table['yscrollcommand'] = self.yscroll.set
self.Frame_table.bind("<Configure>", self.AuxscrollFunction)
self.yscroll.grid_forget()
Number = Label(self.Frame_table, text="", width=4, font = Font, bd = 2, relief="groove")
Number.grid(row=0,column=0,sticky=W)
L = Label(self.Frame_table, text="L", width=8, font = Font, bd = 2, relief="groove")
L.grid(row=0,column=1,sticky=W)
Wid = Label(self.Frame_table, text="W", width=8, font = Font, bd = 2, relief="groove")
Wid.grid(row=0,column=2,sticky=W)
#Subdivisions (defect values)
Wth = self.Data[2]/self.Data[3]
l = self.Data[0]/self.Data[1]
self.var_length = []
self.var_width = []
for i in range(int(self.Max)+1):
if i != 0:
Numbers_label[i] = label + str(i)
Numbers_label[i] = Label(self.Frame_table, text=str(i), width=4, font = Font, bd = 2, relief="groove")
Numbers_label[i].grid(row=i,column=0,sticky=W)
if i <= self.Data[1]:
text = str(l)
else:
text = "0.0"
var_length = StringVar()
self.var_length.append(var_length)
self.length_data[i] = Entry_length + str(i)
self.length_data[i] = Entry(self.Frame_table, width=9, font = Font, bd = 2, relief="groove", textvariable = self.var_length[i-1])
self.var1 = self.length_data[i]
self.var_length[i-1].trace("w", lambda name, index, mode, envio=self: Action.callback(envio))
self.length_data[i].grid(row=i,column=1,sticky=W)
self.length_data[i].insert(0, text)
if i <= self.Data[3]:
text = str(Wth)
else:
text = "0.0"
var_width = StringVar()
self.var_width.append(var_width)
self.width_data[i] = Entry_width + str(i)
self.width_data[i] = Entry(self.Frame_table, width=9, font = Font, bd = 2, relief="groove", textvariable = self.var_width[i-1])
self.var1 = self.width_data[i]
self.var_width[i-1].trace("w", lambda name, index, mode, envio=self: Action.callback(envio))
self.width_data[i].grid(row=i,column=2,sticky=W)
self.width_data[i].insert(0, text)
self.yscroll.pack(side='right', fill = 'y')
def AuxscrollFunction(self,event):
self.canvas_table.configure(scrollregion=self.canvas_table.bbox("all"))
def callback(self, *args):
self.First_Time = self.First_Time+1
if self.First_Time >= 2*int(self.Max) and self.modification == 0:
try:
for i in range(int(self.Max)+1):
if i != 0:
self.Modules[i-1][0] = float(self.length_data[i].get())
self.Modules[i-1][1] = float(self.width_data[i].get())
self.Data[0] = 0
self.Data[2] = 0
for i in range(int(self.Max)):
self.Data[0] = self.Data[0]+self.Modules[i][0]
self.Data[2] = self.Data[2]+self.Modules[i][1]
self.Interface.Length.delete(0, 'end')
self.Interface.Width.delete(0, 'end')
self.Interface.Length.insert(0, str(self.Data[0]))
self.Interface.Width.insert(0, str(self.Data[2]))
#self.var1.focus()
self.Graph()
except ValueError:
pass
def Graph(self):
#---Area---
f=Figure(figsize=(3,3), dpi=100)
a=f.add_subplot(111)
type_line = 'r--' #Línea de borde de área
a.plot([0,self.Data[2]], [0,0], type_line)
a.plot([0,self.Data[2]], [self.Data[0],self.Data[0]], type_line)
a.plot([0,0], [0,self.Data[0]], type_line)
a.plot([self.Data[2],self.Data[2]], [0,self.Data[0]], type_line)
canvas = FigureCanvasTkAgg(f, self.Interface.subframe_graph)
canvas.draw()
canvas.get_tk_widget().place(x=0,y=0)
#--------------------------------------------------------INTERFACE-----------------------------------------------
#---Beginning of the interface---
root = Tk()
#Font
fuente = "TkFixedFont"
Font = (fuente, 10)
Interface(root)
root.mainloop()

Categories

Resources