Custom Tkinter Menu Placement - python

I've been making a game in tkinter to practice my coding skills for future projects however I've come across a stumbling block. I've been reading up on the Tkinter menus and I can't seem to find a way to place them anywhere other than the top of the window. What I am trying to do is to make a drop down selection box that allows you to pick an option and perform a command based on that option but I want it to be placed beside a label in the grid position column=2 row=2. I would like to know if this is possible or not and if not what is another way to do a similar thing.
import tkinter
import threading
import time
import math
from random import randrange
global Stage
Stage = 0
global Coins
Coins = 0
global Actions
Actions = 0
global ActionSpeed
ActionSpeed = 0
global Day
Day = 1
global Metal
Metal = "None"
global Type
Type = "None"
global FormLevel
FormLevel = 0
global Hardness
Hardness = 0
global Sharpness
Sharpness = 0
global Copper
Copper = 0
global Iron
Iron = 0
class simpleapp_tk(tkinter.Tk):
def __init__(self, parent):
tkinter.Tk.__init__(self, parent)
self.parent = parent
self.initialise()
def initialise(self):
self.grid()
self.resizable(False, False)
self.StartUp()
def StartUp(self):
#Story Section 1
self.labelVariableStory1 = tkinter.StringVar()
Story1 = tkinter.Label(self, textvariable=self.labelVariableStory1, anchor = 'w')
Story1.grid(column=0, row=0, sticky='EW')
self.labelVariableStory1.set("A great fire burned through the land two days ago.")
self.labelVariableStory2 = tkinter.StringVar()
Story2 = tkinter.Label(self, textvariable=self.labelVariableStory2, anchor = 'w')
Story2.grid(column=0, row=1, sticky='EW')
self.labelVariableStory2.set("It killed hundreds and left more homeless.")
self.labelVariableStory3 = tkinter.StringVar()
Story3 = tkinter.Label(self, textvariable=self.labelVariableStory3, anchor = 'w')
Story3.grid(column=0, row=2, sticky='EW')
self.labelVariableStory3.set("Now you walk the streets begging for money just to get by.")
self.labelVariableStory4 = tkinter.StringVar()
Story4 = tkinter.Label(self, textvariable=self.labelVariableStory4, anchor = 'w')
Story4.grid(column=0, row=3, sticky='EW')
self.labelVariableStory4.set("This is the start of your journey.")
Story1.after(15000, lambda: Story1.destroy())
Story2.after(15000, lambda: Story2.destroy())
Story3.after(15000, lambda: Story3.destroy())
Story4.after(15000, lambda: Story4.destroy())
self.after(15000, lambda: self.New_Day())
def New_Day(self):
global Coins
global Actions
global ActionSpeed
global Copper
global Iron
Actions = 5 + ActionSpeed
#Basic Information Labels
self.labelVariableInfo1 = tkinter.StringVar()
Info1 = tkinter.Label(self, textvariable=self.labelVariableInfo1, anchor = 'e')
Info1.grid(column=0, row=0, sticky='EW')
self.labelVariableInfo1.set("Coins:")
self.labelVariableInfo2 = tkinter.StringVar()
Info2 = tkinter.Label(self, textvariable=self.labelVariableInfo2, anchor = 'w')
Info2.grid(column=1, row=0, sticky='EW')
self.labelVariableInfo2.set(Coins)
self.labelVariableInfo3 = tkinter.StringVar()
Info3 = tkinter.Label(self, textvariable=self.labelVariableInfo3, anchor = 'e')
Info3.grid(column=2, row=0, sticky='EW')
self.labelVariableInfo3.set("Actions:")
self.labelVariableInfo4 = tkinter.StringVar()
Info4 = tkinter.Label(self, textvariable=self.labelVariableInfo4, anchor = 'w')
Info4.grid(column=3, row=0, sticky='EW')
self.labelVariableInfo4.set(Actions)
self.labelVariableInfo5 = tkinter.StringVar()
Info5 = tkinter.Label(self, textvariable=self.labelVariableInfo5, anchor = 'e')
Info5.grid(column=12, row=0, sticky='EW')
self.labelVariableInfo5.set("Day")
self.labelVariableInfo6 = tkinter.StringVar()
Info6 = tkinter.Label(self, textvariable=self.labelVariableInfo6, anchor = 'w')
Info6.grid(column=13, row=0, sticky='EW')
self.labelVariableInfo6.set(Day)
if Stage == 0:
LabelClear = tkinter.Label(self)
LabelClear.grid(column=4, row=1, columnspan=10, sticky='EW')
WorkButton1 = tkinter.Button(self, text=u"Beg", command=self.Beg)
WorkButton1.grid(column=0, row=1, columnspan=2, sticky='NESW')
SleepButton = tkinter.Button(self, text=u"Sleep", command=self.Sleep)
SleepButton.grid(column=2, row=1, columnspan=2, sticky='NESW')
if Stage >= 1:
#Border Section
self.labelVariableCutOff = tkinter.StringVar()
CutOff = tkinter.Label(self, textvariable=self.labelVariableCutOff)
CutOff.grid(column=0, row=1, columnspan=14, sticky='NESW')
self.labelVariableCutOff.set("+--------------------------------------------------------------+-------------------------------------+")
self.labelVariableBorder = tkinter.StringVar()
Border1 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border1.grid(column=0, row=2, sticky='W')
self.labelVariableBorder.set(" | ")
Border2 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border2.grid(column=13, row=2, sticky='E')
Border3 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border3.grid(column=0, row=3, sticky='W')
Border4 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border4.grid(column=13, row=3, sticky='E')
Border5 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border5.grid(column=0, row=4, sticky='W')
Border6 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border6.grid(column=13, row=4, sticky='E')
Border7 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border7.grid(column=0, row=5, sticky='W')
Border8 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border8.grid(column=13, row=5, sticky='E')
Border9 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border9.grid(column=0, row=6, sticky='W')
Border10 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border10.grid(column=13, row=6, sticky='E')
Border11 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border11.grid(column=0, row=7, sticky='W')
Border12 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border12.grid(column=13, row=7, sticky='E')
Border13 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border13.grid(column=0, row=8, sticky='W')
Border14 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border14.grid(column=13, row=8, sticky='E')
CutOff2 = tkinter.Label(self, textvariable=self.labelVariableCutOff)
CutOff2.grid(column=0, row=9, columnspan=14, sticky='NESW')
Border15 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border15.grid(column=0, row=10, sticky='W')
Border16 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border16.grid(column=13, row=10, sticky='E')
Border17 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border17.grid(column=0, row=11, sticky='W')
Border18 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border18.grid(column=13, row=11, sticky='E')
Border19 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border19.grid(column=0, row=12, sticky='W')
Border20 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border20.grid(column=13, row=12, sticky='E')
Border21 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border21.grid(column=0, row=13, sticky='W')
Border22 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border22.grid(column=13, row=13, sticky='E')
Border23 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border23.grid(column=0, row=14, sticky='W')
Border24 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border24.grid(column=13, row=14, sticky='E')
Border25 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border25.grid(column=7, row=2, sticky='E')
Border26 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border26.grid(column=7, row=3, sticky='E')
Border27 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border27.grid(column=7, row=4, sticky='E')
Border27 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border27.grid(column=7, row=5, sticky='E')
Border28 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border28.grid(column=7, row=6, sticky='E')
Border29 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border29.grid(column=7, row=7, sticky='E')
Border30 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border30.grid(column=7, row=8, sticky='E')
Border31 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border31.grid(column=7, row=10, sticky='E')
Border32 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border32.grid(column=7, row=11, sticky='E')
Border33 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border33.grid(column=7, row=12, sticky='E')
Border34 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border34.grid(column=7, row=13, sticky='E')
Border35 = tkinter.Label(self, textvariable=self.labelVariableBorder)
Border35.grid(column=7, row=14, sticky='E')
CutOff3 = tkinter.Label(self, textvariable=self.labelVariableCutOff)
CutOff3.grid(column=0, row=15, columnspan=14, sticky='NESW')
#Advanced Information Labels (Functional but not Fully Implemented)
self.labelVariableWork1 = tkinter.StringVar()
Work1 = tkinter.Label(self, textvariable=self.labelVariableWork1, anchor='e', fg='black')
Work1.grid(column=9, row=3, columnspan=3, sticky='EW')
self.labelVariableWork1.set("Metal:")
self.labelVariableWork2 = tkinter.StringVar()
Work2 = tkinter.Label(self, textvariable=self.labelVariableWork2, anchor='w', fg='black')
Work2.grid(column=12, row=3, sticky='EW')
self.labelVariableWork2.set(Metal)
self.labelVariableWork3 = tkinter.StringVar()
Work3 = tkinter.Label(self, textvariable=self.labelVariableWork3, anchor='e', fg='black')
Work3.grid(column=9, row=4, columnspan=3, sticky='EW')
self.labelVariableWork3.set("Type:")
self.labelVariableWork4 = tkinter.StringVar()
Work4 = tkinter.Label(self, textvariable=self.labelVariableWork4, anchor='w', fg='black')
Work4.grid(column=12, row=4, sticky='EW')
self.labelVariableWork4.set(Type)
self.labelVariableWork5 = tkinter.StringVar()
Work5 = tkinter.Label(self, textvariable=self.labelVariableWork5, anchor='e', fg='black')
Work5.grid(column=9, row=5, columnspan=3, sticky='EW')
self.labelVariableWork5.set("Forming:")
self.labelVariableWork6 = tkinter.StringVar()
Work6 = tkinter.Label(self, textvariable=self.labelVariableWork6, anchor='w', fg='black')
Work6.grid(column=12, row=5, sticky='EW')
self.labelVariableWork6.set("{0}%".format(FormLevel))
self.labelVariableWork7 = tkinter.StringVar()
Work7 = tkinter.Label(self, textvariable=self.labelVariableWork7, anchor='e', fg='black')
Work7.grid(column=9, row=6, columnspan=3, sticky='EW')
self.labelVariableWork7.set("Hardening:")
self.labelVariableWork8 = tkinter.StringVar()
Work8 = tkinter.Label(self, textvariable=self.labelVariableWork8, anchor='w', fg='black')
Work8.grid(column=12, row=6, sticky='EW')
self.labelVariableWork8.set("{0}%".format(Hardness))
self.labelVariableWork9 = tkinter.StringVar()
Work9 = tkinter.Label(self, textvariable=self.labelVariableWork9, anchor='e', fg='black')
Work9.grid(column=9, row=7, columnspan=3, sticky='EW')
self.labelVariableWork9.set("Sharpening:")
self.labelVariableWork10 = tkinter.StringVar()
Work10 = tkinter.Label(self, textvariable=self.labelVariableWork10, anchor='w', fg='black')
Work10.grid(column=12, row=7, sticky='EW')
self.labelVariableWork10.set("{0}%".format(Sharpness))
#Label that is meant to be next to the menu
Label1 = tkinter.Label(self, text="Buy:", anchor='e')
Label1.grid(column=1, row=2, sticky='EW')
#The Latest version of my unworking menu code
'''BuyMenu = tkinter.Menu()
Menu1 = tkinter.MenuButton(menu=BuyMenu)
BuyMenu.add_cascade(label="Choose Metal", menu=BuyMenu)
BuyMenu.add_command(label="Copper C: 15", command=self.BuyCopper)
BuyMenu.add_command(label="Iron C: 25", command=self.BuyIron)
Menu1.grid(column=2, row=2, sticky='EW')'''
#Resource Information
Info7 = tkinter.Label(self, text="Copper:", anchor='e')
Info7.grid(column=1, row=3, sticky='EW')
self.labelVariableResource1 = tkinter.StringVar()
Resource1 = tkinter.Label(self, textvariable=self.labelVariableResource1, anchor='w')
Resource1.grid(column=2, row=3, sticky='EW')
self.labelVariableResource1.set(Copper)
Info8 = tkinter.Label(self, text="Iron:", anchor='e')
Info8.grid(column=1, row=4, sticky='EW')
self.labelVariableResource2 = tkinter.StringVar()
Resource1 = tkinter.Label(self, textvariable=self.labelVariableResource2, anchor='w')
Resource1.grid(column=2, row=4, sticky='EW')
self.labelVariableResource2.set(Iron)
#Stage 0 Commands
def Beg(self):
global Actions
global Coins
if Actions != 0:
Actions -= 1
Coins += 1
Bonus = randrange(1,6)
if Bonus == 5:
Coins +=1
self.labelVariableInfo2.set(Coins)
self.labelVariableInfo4.set(Actions)
def Sleep(self):
global Day
global Coins
Day += 1
if Stage == 0:
Coins -= 2
DarkLabel = tkinter.Label(self, bg='black')
DarkLabel.grid(column=0, row=0, columnspan=14, rowspan=2, sticky='NESW')
self.after(5000, lambda: DarkLabel.destroy())
if Day == 5:
self.after(5000, lambda: self.Story1())
Coins += 50
else:
self.after(5000, lambda: self.New_Day())
#Story Section 2
def Story1(self):
global Stage
self.labelVariableInfo5.set("")
self.labelVariableInfo6.set("")
self.labelVariableStory1 = tkinter.StringVar()
Story1 = tkinter.Label(self, textvariable=self.labelVariableStory1, anchor = 'w')
Story1.grid(column=0, row=0, columnspan=4, sticky='EW')
self.labelVariableStory1.set("On the fifth day an old man comes up to you.")
self.labelVariableStory2 = tkinter.StringVar()
Story2 = tkinter.Label(self, textvariable=self.labelVariableStory2, anchor = 'w')
Story2.grid(column=0, row=1, columnspan=4, sticky='NESW')
self.labelVariableStory2.set("'It pains me to see a young person in need.'")
self.labelVariableStory3 = tkinter.StringVar()
Story3 = tkinter.Label(self, textvariable=self.labelVariableStory3, anchor = 'w')
Story3.grid(column=0, row=2, columnspan=4, sticky='EW')
self.labelVariableStory3.set("'I'm almost at the end of my days and I have no children.'")
self.labelVariableStory4 = tkinter.StringVar()
Story4 = tkinter.Label(self, textvariable=self.labelVariableStory4, anchor = 'w')
Story4.grid(column=0, row=3, columnspan=4, sticky='EW')
self.labelVariableStory4.set("'I will teach you all I can and leave you my forge.'")
Story1.after(15000, lambda: Story1.destroy())
Story2.after(15000, lambda: Story2.destroy())
Story3.after(15000, lambda: Story3.destroy())
Story4.after(15000, lambda: Story4.destroy())
Stage += 1
self.after(15000, lambda: self.New_Day())
#Stage 1 Commands (These are to be triggered by the menu)
def BuyCopper(self):
global Coins
global Copper
if Coins >= 15:
Coins -= 15
Copper += 1
self.labelVariableInfo2.set(Coins)
self.labelVariableResource1.set(Copper)
def BuyIron(self):
global Coins
global Iron
if Coins >= 25:
Coins -= 25
Iron += 1
self.labelVariableInfo2.set(Coins)
self.labelVariableResource2.set(Iron)
#GUI loop
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('Smithy')
app.mainloop()
I have now included my whole code with the exception of commenting out my unworking menu code.

You would need an option menu or a ComboBox. They are menus but on the page not at the top of the screen.
Here is the code to add options to the OptionMenu:
from Tkinter import *
root=Tk()
def change(value):
options.append("YOUR_OPTION_HERE")
menu=drop["menu"]
menu.delete("0", END)
for string in options:
menu.add_command(label=string, command=lambda value=string: var.set(value))
options=["hello", "goodbye", "welcome"]
var=StringVar()
drop=OptionMenu(root, var, *options, command=change)
drop.config(width=15)
drop.pack()
root.mainloop()

Related

How to solve the "bad window path name ".!labelframe.!canvas.!frame" error in tkinter python?

This is my code:
mycanvas = Canvas(self.search_result_frame)
mycanvas.pack(side=LEFT)
yscrollbar = ttk.Scrollbar(self.search_result_frame, orient="vertical", command=mycanvas.yview)
yscrollbar.pack(side=RIGHT, fill=Y)
mycanvas.configure(yscrollcommand=yscrollbar.set)
mycanvas.bind('<Configure>', lambda e: mycanvas.configure(scrollregion = mycanvas.bbox('all')))
self.sample_frame = Frame(mycanvas)
mycanvas.create_window((0,0), window=self.sample_frame, anchor=E)
for widget in self.search_result_frame.winfo_children():
widget.destroy()
if len(matching_bills) > 0:
for bill in matching_bills:
with open(f'{self.bill_folder}//{bill}//data//bill_details.json', 'r') as bill_json_file:
bill_details = json.loads(bill_json_file.read())
customer_name = bill_details["customer_details"][0]
payment_method = bill_details["payment_method"]
date_of_issue = bill_details["date_of_issue"]
date_of_issue = datetime.strptime(date_of_issue, "%d/%m/%Y")
date_of_issue = date_of_issue.strftime("%d %b %Y")
# # -------------------- Search Result Frame Contents
result_frame = Frame(self.sample_frame, bg=self.bg3, bd=5, relief=GROOVE)
result_frame.pack(fill=BOTH, pady=2)
result_billno_lbl = Label(result_frame, text=bill, bg=self.bg1, fg="#FFF", font=self.search_results_font1, padx=22, pady=3)
result_billno_lbl.grid(row=0, column=0, padx=50, pady=8, sticky=W)
billed_to_lbl = Label(result_frame, text=f"Billed To - {customer_name}", bg=self.bg1, fg="#FFF", font=self.search_results_font2, bd=2, relief=RAISED, padx=12, pady=3)
billed_to_lbl.grid(row=0, column=1, padx=80, sticky=W)
billed_type_lbl = Label(result_frame, text=f"Bill Type - {payment_method}", bg=self.bg1, fg="#FFF", font=self.search_results_font2, bd=2, relief=RAISED, padx=12, pady=3)
billed_type_lbl.grid(row=0, column=2, sticky=W)
issued_on_lbl = Label(result_frame, text=f"Issued On - {date_of_issue}", bg=self.bg1, fg="#FFF",
font=self.search_results_font2, bd=2, relief=RAISED, padx=12, pady=3)
issued_on_lbl.grid(row=0, column=3, padx=80, sticky=W)
view_btn = Button(result_frame, text="View", font="Comicsan 14", bd=2, relief=GROOVE, bg="#000", fg="#FFF", padx=1, command=lambda bill=bill: self.view_bill(bill))
view_btn.grid(row=0, column=4, padx=3, columnspan=2, sticky=W)
elif len(matching_bills) == 0:
for widgets in self.search_result_frame.winfo_children():
widgets.destroy()
no_result_lbl = Label(self.search_result_frame, text=f"No search result found for {bill_cat}", font=self.search_results_font1, bg=self.bg3, fg="#FFF")
no_result_lbl.pack(fill=X)
When I run it, it shows me the bad window path name ".!labelframe.!canvas.!frame error and when I try to do the same thing without object-oriented in tkinter then it works well !

How to Make Plot Show up?

So I am trying to create this function to make a plot of a mass spring damper system and we should be able to basically change whatever we like, the values for the function and the sliders should affect the plot as well, i'm having trouble trying to get my function plotted. The error is coming within the function where I am trying to use my solveMBK function inside my PlotWindow function, I am not sure how to include the values from my sliders as well as the other values that are inputted in the start up window. Here is a look at my code:
import tkinter as tk
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import numpy as np
def solveMBK(inlist):
x0 = inlist[0]
dx0 = inlist[1]
dt = inlist[2]
m = inlist[3]
b = inlist[4]
k = inlist[5]
tf = inlist[6]
Z = inlist[7]
t = np.arange(0,tf,dt)
z0 = np.zeros_like(t)
z1 = np.zeros_like(t)
z0[0] = x0
z1[0] = dx0
for c in range(len(t)-1):
z0[c+1] = z0[c] + z1[c]*dt
z1[c+1] = z1[c] + ((ABradiobutton(Z,t[c]) - k*z0[c] - b*z1[c]) / m)
x = z0
return t,x
def ABradiobutton(Z, t):
if Z == 1:
A = float(A_entry.get())
return A
elif Z == 2:
B = float(B_entry.get())
return np.sin(B*t)
def PlotWindow():
root1 = tk.Tk()
root1.title("Plot")
Mmin = float(Mmin_entry.get())
Mmax = float(Mmax_entry.get())
bmin = float(bmin_entry.get())
bmax = float(bmax_entry.get())
kmin = float(kmin_entry.get())
kmax = float(kmax_entry.get())
mscale = tk.Scale(root1, from_=Mmin, to=Mmax, label="m", bd=2, length=200, orient=tk.HORIZONTAL, command = funcPlot)
mscale.set((Mmin+Mmax)/2)
mscale.grid(row=1, column=0)
bscale = tk.Scale(root1, from_=bmin, to=bmax, label="b", bd=2, length=200, orient=tk.HORIZONTAL, command = funcPlot)
bscale.set((bmin+bmax)/2)
bscale.grid(row=3, column=0)
kscale = tk.Scale(root1, from_=kmin, to=kmax, label="k", bd=2, length=200, orient=tk.HORIZONTAL, command = funcPlot)
kscale.set((kmin+kmax)/2)
kscale.grid(row=5, column=0)
tk.Label(root1, text = " ").grid(row=6, column=0)
tk.Button(root1, text="Back", command=root1.destroy).grid(row=7, column=0)
Graph_Frame = tk.Frame(root1)
Graph_Frame.grid(row=2, column=2, columnspan=10, rowspan=10)
Fig = Figure(figsize=(5.5,4))
a = Fig.add_subplot(111)
if Radio_Var == 1:
t,x = solveMBK(str(mscale.get()), str(bscale.get()), str(kscale.get()), str(A_entry.get()), str(x0_Entry.get()), str(dxdt_Entry.get()), str(tfinal_entry.get()), str(dt_entry.get()))
a.plot(t,x)
# elif Radio_Var == 2:
# t,x = solveMBK()
# a.plot(t,x)
tk.Label(Graph_Frame, text = "Mass-Spring-Damper Plot").pack()
canvas = FigureCanvasTkAgg(Fig, Graph_Frame)
canvas.draw()
canvas.get_tk_widget().pack()
toolbar = NavigationToolbar2Tk(canvas, Graph_Frame)
toolbar.update()
canvas.get_tk_widget().pack()
def CloseWindow():
root.quit()
root.destroy()
exit()
def funcPlot(input_list, mscale, bscale, kscale, a, canvas, event=None):
input_list[0]=float(x0_Entry.get())
input_list[1]=float(dxdt_Entry.get())
input_list[2]=float(dt_entry.get())
input_list[3]=float(mscale.get())
input_list[4]=float(bscale.get())
input_list[5]=float(kscale.get())
input_list[6]=float(tfinal_entry.get())
input_list[7]=float(Radio_Var.get())
data = solveMBK(input_list)
a.plot(data[0], data[1])
canvas.draw()
return
root = tk.Tk()
root.title("Numerical solution of a second order differential equation")
tk.Label(root, text = "Differential Equation:").grid(row=0, column=0, sticky=tk.E)
tk.Label(root, text = "m d2x/dt2 + b dx/dt + kx = f(x)").grid(row=0, column=1)
x0_Start = tk.IntVar()
x0_Start.set("0")
x0_Entry = tk.Entry(root, width=7, textvariable = x0_Start)
tk.Label(root, text = "x(0) = ").grid(row=1, column=0, stick=tk.E), x0_Entry.grid(row=1, column=1, sticky=tk.W)
dxdt_Start = tk.IntVar()
dxdt_Start.set("0")
dxdt_Entry = tk.Entry(root, width=7, textvariable = dxdt_Start)
tk.Label(root, text = "dx(0)/dt= ").grid(row=2, column=0, sticky=tk.E), dxdt_Entry.grid(row=2, column=1, sticky=tk.W)
A_start = tk.IntVar()
A_start.set("1")
A_entry = tk.Entry(root, width=7, textvariable = A_start)
tk.Label(root, text = "A = ").grid(row=6, column=1, sticky=tk.E), A_entry.grid(row=6, column=2, sticky=tk.W)
B_start = tk.IntVar()
B_start.set("0")
B_entry = tk.Entry(root, width=7, textvariable=B_start)
tk.Label(root, text= "B =").grid(row=7,column=1, sticky=tk.E), B_entry.grid(row=7, column=2, sticky=tk.W)
tk.Label(root, text = " ").grid(row=5, column=0, sticky=tk.E)
Radio_Var = tk.IntVar()
tk.Radiobutton(root, text="A", value = 1, variable=Radio_Var).grid(row=6, column=1, sticky = tk.W)
tk.Radiobutton(root, text="sin(Bt)", value = 2, variable=Radio_Var).grid(row=7, column=1, sticky = tk.W)
Radio_Var.set(1)
tk.Label(root, text = "f(x) = ").grid(row=6, column=0, sticky=tk.E)
tk.Label(root, text = " ").grid(row=8, column=0, sticky=tk.E)
tfinal_start = tk.IntVar()
tfinal_start.set("10")
tfinal_entry = tk.Entry(root, width = 7, textvariable=tfinal_start)
tk.Label(root, text = "tfinal = ").grid(row=9, column=0, sticky=tk.E), tfinal_entry.grid(row=9, column=1, sticky=tk.W)
dt_start = tk.IntVar()
dt_start.set("0.001")
dt_entry = tk.Entry(root, width = 7, textvariable=dt_start)
tk.Label(root, text = "dt = ").grid(row=9, column=1, sticky=tk.E), dt_entry.grid(row=9, column=2, sticky=tk.W)
tk.Label(root, text = " ").grid(row=10, column=0, sticky=tk.E)
Mmin_start = tk.IntVar()
Mmin_start.set("1")
Mmin_entry = tk.Entry(root, width=7, textvariable=Mmin_start)
tk.Label(root, text = "Mmin = ").grid(row=11, column=0, sticky=tk.E), Mmin_entry.grid(row=11, column=1, sticky=tk.W)
Mmax_start = tk.IntVar()
Mmax_start.set("100")
Mmax_entry = tk.Entry(root, width=7, textvariable=Mmax_start)
tk.Label(root, text = "Mmax = ").grid(row=11,column=1, sticky=tk.E), Mmax_entry.grid(row=11, column=2, sticky=tk.W)
bmin_start = tk.IntVar()
bmin_start.set("1")
bmin_entry = tk.Entry(root, width=7, textvariable=bmin_start)
tk.Label(root, text = "bmin = ").grid(row=12, column=0, sticky=tk.E), bmin_entry.grid(row=12, column=1, sticky=tk.W)
bmax_start = tk.IntVar()
bmax_start.set("250")
bmax_entry = tk.Entry(root, width=7, textvariable=bmax_start)
tk.Label(root, text= "bmax = ").grid(row=12, column=1, sticky=tk.E), bmax_entry.grid(row=12,column=2,sticky=tk.W)
kmin_start = tk.IntVar()
kmin_start.set("1")
kmin_entry = tk.Entry(root, width=7, textvariable=kmin_start)
tk.Label(root, text= "kmin = ").grid(row=13, column=0, sticky=tk.E), kmin_entry.grid(row=13, column=1, sticky=tk.W)
kmax_start = tk.IntVar()
kmax_start.set("500")
kmax_entry = tk.Entry(root, width=7, textvariable=kmax_start)
tk.Label(root, text="kmax = ").grid(row=13, column=1, sticky=tk.E), kmax_entry.grid(row=13, column=2, sticky=tk.W)
tk.Button(root, text = "Quit", command=CloseWindow, width=10).grid(row=14, column=0)
tk.Button(root, text= "Plot", command=PlotWindow, width=10).grid(row=14, column=3)
root.mainloop()
Any help would be appreciated, thank you!
You're passing funcPlot as the command for Scale to call:
mscale = tk.Scale(root1, ..., command=funcPlot)
According to the documentation, command is:
A procedure to be called every time the slider is moved. This
procedure will be passed one argument, the new scale value.
But instead of taking one argument, your funcPlot() function requires six arguments:
def funcPlot(input_list, mscale, bscale, kscale, a, canvas, event=None):
Which leads to the error:
TypeError: funcPlot() missing 5 required positional arguments: 'mscale', 'bscale', 'kscale', 'a', and 'canvas'
You need to rethink how this is supposed to work. Below is my rework of your code. I got around the problem above by using global variables -- I'm not proud of that. I also had to rework the way your plot gets embedded in Tk as what you had wasn't working:
import tkinter as tk
import numpy as np
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
def solveMBK(inlist):
x0, dx0, dt, m, b, k, tf, Z = inlist
t = np.arange(0, tf, dt)
z0 = np.zeros_like(t)
z1 = np.zeros_like(t)
z0[0] = x0
z1[0] = dx0
for c in range(len(t) - 1):
z0[c + 1] = z0[c] + z1[c] * dt
z1[c + 1] = z1[c] + ((ABradiobutton(Z, t[c]) - k * z0[c] - b * z1[c]) / m)
return t, z0
def ABradiobutton(Z, t):
if Z == 1:
A = float(A_entry.get())
return A
if Z == 2:
B = float(B_entry.get())
return np.sin(B * t)
def PlotWindow():
global mscale, bscale, kscale, subplot, figure_canvas
plot_window = tk.Toplevel(root)
plot_window.title("Plot")
Mmin = float(Mmin_entry.get())
Mmax = float(Mmax_entry.get())
bmin = float(bmin_entry.get())
bmax = float(bmax_entry.get())
kmin = float(kmin_entry.get())
kmax = float(kmax_entry.get())
mscale = tk.Scale(plot_window, from_=Mmin, to=Mmax, label="m", bd=2, length=200, orient=tk.HORIZONTAL, command=funcPlot)
mscale.set((Mmin + Mmax) / 2)
mscale.grid(row=1, column=0)
bscale = tk.Scale(plot_window, from_=bmin, to=bmax, label="b", bd=2, length=200, orient=tk.HORIZONTAL, command=funcPlot)
bscale.set((bmin + bmax) / 2)
bscale.grid(row=3, column=0)
kscale = tk.Scale(plot_window, from_=kmin, to=kmax, label="k", bd=2, length=200, orient=tk.HORIZONTAL, command=funcPlot)
kscale.set((kmin + kmax) / 2)
kscale.grid(row=5, column=0)
tk.Label(plot_window, text=" ").grid(row=6, column=0)
tk.Button(plot_window, text="Back", command=plot_window.destroy).grid(row=7, column=0)
graph_frame = tk.Frame(plot_window)
graph_frame.grid(row=2, column=2, columnspan=10, rowspan=10)
figure = Figure(figsize=(5.5, 4))
subplot = figure.add_subplot(111)
if Radio_Var.get() == 1:
t, x = solveMBK([float(mscale.get()), float(bscale.get()), float(kscale.get()), float(A_entry.get()), float(x0_Entry.get()), float(dxdt_Entry.get()), float(tfinal_entry.get()), float(dt_entry.get())])
subplot.plot(t, x)
# elif Radio_Var.get() == 2:
# t, x = solveMBK()
# subplot.plot(t, x)
figure_canvas = FigureCanvasTkAgg(figure, master=graph_frame)
figure_canvas.draw()
figure_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(figure_canvas, graph_frame)
toolbar.update()
figure_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
tk.Label(graph_frame, text="Mass-Spring-Damper Plot").pack()
def CloseWindow():
root.quit()
root.destroy()
exit()
def funcPlot(event):
input_list = []
input_list.append(float(x0_Entry.get()))
input_list.append(float(dxdt_Entry.get()))
input_list.append(float(dt_entry.get()))
input_list.append(float(mscale.get()))
input_list.append(float(bscale.get()))
input_list.append(float(kscale.get()))
input_list.append(float(tfinal_entry.get()))
input_list.append(float(Radio_Var.get()))
t, x = solveMBK(input_list)
subplot.plot(t, x)
figure_canvas.draw()
figure_canvas = subplot = mscale = bscale = kscale = None
root = tk.Tk()
root.title("Numerical solution of a second order differential equation")
tk.Label(root, text="Differential Equation:").grid(row=0, column=0, sticky=tk.E)
tk.Label(root, text="m d2x/dt2 + b dx/dt + kx = f(x)").grid(row=0, column=1)
tk.Label(root, text="x(0) = ").grid(row=1, column=0, stick=tk.E)
x0_Start = tk.IntVar()
x0_Start.set("0")
x0_Entry = tk.Entry(root, width=7, textvariable=x0_Start)
x0_Entry.grid(row=1, column=1, sticky=tk.W)
tk.Label(root, text="dx(0)/dt = ").grid(row=2, column=0, sticky=tk.E)
dxdt_Start = tk.IntVar()
dxdt_Start.set("0")
dxdt_Entry = tk.Entry(root, width=7, textvariable=dxdt_Start)
dxdt_Entry.grid(row=2, column=1, sticky=tk.W)
tk.Label(root, text=" ").grid(row=5, column=0, sticky=tk.E)
Radio_Var = tk.IntVar()
Radio_Var.set(1)
tk.Label(root, text="f(x) = ").grid(row=6, column=0, sticky=tk.E)
tk.Radiobutton(root, text="A", value=1, variable=Radio_Var).grid(row=6, column=1, sticky=tk.W)
tk.Label(root, text="A = ").grid(row=6, column=1, sticky=tk.E)
A_start = tk.IntVar()
A_start.set("1")
A_entry = tk.Entry(root, width=7, textvariable=A_start)
A_entry.grid(row=6, column=2, sticky=tk.W)
tk.Radiobutton(root, text="sin(Bt)", value=2, variable=Radio_Var).grid(row=7, column=1, sticky=tk.W)
tk.Label(root, text="B =").grid(row=7, column=1, sticky=tk.E)
B_start = tk.IntVar()
B_start.set("0")
B_entry = tk.Entry(root, width=7, textvariable=B_start)
B_entry.grid(row=7, column=2, sticky=tk.W)
tk.Label(root, text=" ").grid(row=8, column=0, sticky=tk.E)
tk.Label(root, text="tfinal = ").grid(row=9, column=0, sticky=tk.E)
tfinal_start = tk.IntVar()
tfinal_start.set("10")
tfinal_entry = tk.Entry(root, width=7, textvariable=tfinal_start)
tfinal_entry.grid(row=9, column=1, sticky=tk.W)
tk.Label(root, text="dt = ").grid(row=9, column=1, sticky=tk.E)
dt_start = tk.IntVar()
dt_start.set("0.001")
dt_entry = tk.Entry(root, width=7, textvariable=dt_start)
dt_entry.grid(row=9, column=2, sticky=tk.W)
tk.Label(root, text=" ").grid(row=10, column=0, sticky=tk.E)
tk.Label(root, text="Mmin = ").grid(row=11, column=0, sticky=tk.E)
Mmin_start = tk.IntVar()
Mmin_start.set("1")
Mmin_entry = tk.Entry(root, width=7, textvariable=Mmin_start)
Mmin_entry.grid(row=11, column=1, sticky=tk.W)
tk.Label(root, text="Mmax = ").grid(row=11, column=1, sticky=tk.E)
Mmax_start = tk.IntVar()
Mmax_start.set("100")
Mmax_entry = tk.Entry(root, width=7, textvariable=Mmax_start)
Mmax_entry.grid(row=11, column=2, sticky=tk.W)
tk.Label(root, text="bmin = ").grid(row=12, column=0, sticky=tk.E)
bmin_start = tk.IntVar()
bmin_start.set("1")
bmin_entry = tk.Entry(root, width=7, textvariable=bmin_start)
bmin_entry.grid(row=12, column=1, sticky=tk.W)
tk.Label(root, text="bmax = ").grid(row=12, column=1, sticky=tk.E)
bmax_start = tk.IntVar()
bmax_start.set("250")
bmax_entry = tk.Entry(root, width=7, textvariable=bmax_start)
bmax_entry.grid(row=12, column=2, sticky=tk.W)
tk.Label(root, text="kmin = ").grid(row=13, column=0, sticky=tk.E)
kmin_start = tk.IntVar()
kmin_start.set("1")
kmin_entry = tk.Entry(root, width=7, textvariable=kmin_start)
kmin_entry.grid(row=13, column=1, sticky=tk.W)
tk.Label(root, text="kmax = ").grid(row=13, column=1, sticky=tk.E)
kmax_start = tk.IntVar()
kmax_start.set("500")
kmax_entry = tk.Entry(root, width=7, textvariable=kmax_start)
kmax_entry.grid(row=13, column=2, sticky=tk.W)
tk.Button(root, text="Quit", command=CloseWindow, width=10).grid(row=14, column=0)
tk.Button(root, text="Plot", command=PlotWindow, width=10).grid(row=14, column=3)
root.mainloop()

Run more loops at the same time? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
First of all, I have to say that I'm a beginner in Python. These are my first steps in creating a class. And now my question.On that picture, I presented what my code should work.
Start the program (Run)
Check what instruments should be power on. There are three
possibilities and you can power one, two or all three Units at the
same time. (Power #A/B/C)
Furthermore, with each power unit additional you can turn on
Temperatur sensor (Temp. #A,B,C)
Depending on which units are involved to run a Loop #A, #B, #C or
for example two units #B,#C or perhaps all three.This is actually my Problem and question. How can be able to simultaneously also at
the same time, run two or maybe even three loops ?
I hope you can give me some advice and help in solving my problem.
Below I will put my code so you can refer and pay Attention what I could change or improve in my code.
import Tkinter
import visa, time, datetime
from ttk import *
from tkFileDialog import *
import tkMessageBox, os
import numpy as np
rm = visa.ResourceManager()
inst = rm.list_resources()
class Interface:
def __init__(self, parent):
self.parent = parent
parent.title("Cycling")
local_directory = os.path.dirname(os.path.realpath(__file__))
self.dataname = "/does/not/exist"
# Frame
self.frame_instruments = Tkinter.Frame(parent, bg='', colormap='new')
self.frame_settings = Tkinter.Frame(parent, bg='', colormap='new')
self.frame_image = Tkinter.Frame(parent, bg='', colormap='new')
# Labelframe
self.lframe_instrumet_a = Tkinter.LabelFrame(self.frame_instruments, text="Choose an Instruments - #A", padx=8, pady=9)
self.lframe_settings_a = Tkinter.LabelFrame(self.frame_instruments, text="Settings - #A", padx=7, pady=11)
self.lframe_instrumet_b = Tkinter.LabelFrame(self.frame_instruments, text="Choose an Instruments - #B", padx=8, pady=9)
self.lframe_settings_b = Tkinter.LabelFrame(self.frame_instruments, text="Settings - #B", padx=7, pady=11)
self.lframe_instrumet_c = Tkinter.LabelFrame(self.frame_instruments, text="Choose an Instruments - #C", padx=8, pady=9)
self.lframe_settings_c = Tkinter.LabelFrame(self.frame_instruments, text="Settings - #C", padx=7, pady=11)
# Combobox
#A
self.choices_power_supply_a_var = Tkinter.StringVar()
self.choices_power_supply_a_var.set(inst[0])
self.combo_power_supply_a = Combobox(self.lframe_instrumet_a, values=inst, textvariable=self.choices_power_supply_a_var)
self.choices_multimeter_a_var = Tkinter.StringVar()
self.choices_multimeter_a_var.set(inst[0])
self.combo_multimeter_a = Combobox(self.lframe_instrumet_a, values=inst, textvariable=self.choices_multimeter_a_var)
#B
self.choices_power_supply_b_var = Tkinter.StringVar()
self.choices_power_supply_b_var.set(inst[0])
self.combo_power_supply_b = Combobox(self.lframe_instrumet_b, values=inst, textvariable=self.choices_power_supply_b_var)
self.choices_multimeter_b_var = Tkinter.StringVar()
self.choices_multimeter_b_var.set(inst[0])
self.combo_multimeter_b = Combobox(self.lframe_instrumet_b, values=inst, textvariable=self.choices_multimeter_b_var)
#C
self.choices_power_supply_c_var = Tkinter.StringVar()
self.choices_power_supply_c_var.set(inst[0])
self.combo_power_supply_c = Combobox(self.lframe_instrumet_c, values=inst, textvariable=self.choices_power_supply_c_var)
self.choices_multimeter_c_var = Tkinter.StringVar()
self.choices_multimeter_c_var.set(inst[0])
self.combo_multimeter_c = Combobox(self.lframe_instrumet_c, values=inst, textvariable=self.choices_multimeter_c_var)
# Menu
menu = Tkinter.Menu(parent, tearoff=0)
parent.config(menu=menu)
filemenu = Tkinter.Menu(parent, tearoff=0)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='Create New File...', command=lambda: self.save_file())
helpmenu = Tkinter.Menu(menu, tearoff=0)
menu.add_cascade(label='?', menu=helpmenu)
helpmenu.add_command(label='About', command=lambda: self.about())
# Label
#A
self.label_power_supply_a = Tkinter.Label(self.lframe_instrumet_a, text="Power Supply 2200: ")
self.label_multimeter_a = Tkinter.Label(self.lframe_instrumet_a, text="Multimeter 2700: ")
self.label_voltage_range_a = Tkinter.Label(self.lframe_settings_a, text='Voltage Range [V]')
self.label_over_voltage_a = Tkinter.Label(self.lframe_settings_a, text='Over Voltage Protection [V]')
self.label_voltage_set_a = Tkinter.Label(self.lframe_settings_a, text='Set Voltage [V]')
self.label_heat_set_a = Tkinter.Label(self.lframe_settings_a, text='Heat.Set [A]')
self.label_meas_set_a = Tkinter.Label(self.lframe_settings_a, text='Meas. Set [A]')
self.label_set_time_a = Tkinter.Label(self.lframe_settings_a, text='Time Limit [s]')
self.label_set_delay_a = Tkinter.Label(self.lframe_settings_a, text='Measurement Delay [s]')
self.label_set_repeat_a = Tkinter.Label(self.lframe_settings_a, text='Repeat')
#B
self.label_power_supply_b = Tkinter.Label(self.lframe_instrumet_b, text="Power Supply 2200: ")
self.label_multimeter_b = Tkinter.Label(self.lframe_instrumet_b, text="Multimeter 2700: ")
self.label_voltage_range_b = Tkinter.Label(self.lframe_settings_b, text='Voltage Range [V]')
self.label_over_voltage_b = Tkinter.Label(self.lframe_settings_b, text='Over Voltage Protection [V]')
self.label_voltage_set_b = Tkinter.Label(self.lframe_settings_b, text='Set Voltage [V]')
self.label_heat_set_b = Tkinter.Label(self.lframe_settings_b, text='Heat.Set [A]')
self.label_meas_set_b = Tkinter.Label(self.lframe_settings_b, text='Meas. Set [A]')
self.label_set_time_b = Tkinter.Label(self.lframe_settings_b, text='Time Limit [s]')
self.label_set_delay_b = Tkinter.Label(self.lframe_settings_b, text='Measurement Delay [s]')
self.label_set_repeat_b = Tkinter.Label(self.lframe_settings_b, text='Repeat')
#C
self.label_power_supply_c = Tkinter.Label(self.lframe_instrumet_c, text="Power Supply 2200: ")
self.label_multimeter_c = Tkinter.Label(self.lframe_instrumet_c, text="Multimeter 2700: ")
self.label_voltage_range_c = Tkinter.Label(self.lframe_settings_c, text='Voltage Range [V]')
self.label_over_voltage_c = Tkinter.Label(self.lframe_settings_c, text='Over Voltage Protection [V]')
self.label_voltage_set_c = Tkinter.Label(self.lframe_settings_c, text='Set Voltage [V]')
self.label_heat_set_c = Tkinter.Label(self.lframe_settings_c, text='Heat.Set [A]')
self.label_meas_set_c = Tkinter.Label(self.lframe_settings_c, text='Meas. Set [A]')
self.label_set_time_c = Tkinter.Label(self.lframe_settings_c, text='Time Limit [s]')
self.label_set_delay_c = Tkinter.Label(self.lframe_settings_c, text='Measurement Delay [s]')
self.label_set_repeat_c = Tkinter.Label(self.lframe_settings_c, text='Repeat')
# Checkbutton
#A
self.temp_sensor_a_var = Tkinter.IntVar()
self.check_temp_sensor_a = Checkbutton(self.lframe_instrumet_a, text="Temperatursensor - #A", variable=self.temp_sensor_a_var,
onvalue=1, offvalue=0)
self.instrument_var_a = Tkinter.IntVar()
self.check_instrument_a = Checkbutton(self.lframe_settings_a, text="Instrument - #A", variable=self.instrument_var_a,
onvalue=1, offvalue=0)
#B
self.temp_sensor_b_var = Tkinter.IntVar()
self.check_temp_sensor_b = Checkbutton(self.lframe_instrumet_b, text="Temperatursensor - #B", variable=self.temp_sensor_b_var,
onvalue=1, offvalue=0)
self.instrument_var_b = Tkinter.IntVar()
self.check_instrument_b = Checkbutton(self.lframe_settings_b, text="Instrument - #B", variable=self.instrument_var_b,
onvalue=1, offvalue=0)
#C
self.temp_sensor_c_var = Tkinter.IntVar()
self.check_temp_sensor_c = Checkbutton(self.lframe_instrumet_c, text="Temperatursensor - #C", variable=self.temp_sensor_c_var,
onvalue=1, offvalue=0)
self.instrument_var_c = Tkinter.IntVar()
self.check_instrument_c = Checkbutton(self.lframe_settings_c, text="Instrument - #C", variable=self.instrument_var_c,
onvalue=1, offvalue=0)
# Entry/Spinbox
#A
self.voltage_range_a_var = Tkinter.IntVar()
self.spin_voltage_range_a = Tkinter.Spinbox(self.lframe_settings_a, textvariable=self.voltage_range_a_var, width=5,
from_=0, to=30, justify='right')
self.over_voltage_a_var = Tkinter.IntVar()
self.spin_over_voltage_a = Tkinter.Spinbox(self.lframe_settings_a, textvariable=self.over_voltage_a_var, width=5,
from_=0, to=30, justify='right')
self.heat_set_a_var = Tkinter.IntVar()
self.entry_heat_set_a = Tkinter.Entry(self.lframe_settings_a, textvariable=self.heat_set_a_var, width=7, justify='right')
self.meas_set_a_var = Tkinter.IntVar()
self.entry_meas_set_a = Tkinter.Entry(self.lframe_settings_a, textvariable=self.meas_set_a_var, width=7, justify='right')
self.voltage_set_a_var = Tkinter.IntVar()
self.entry_voltage_set_a = Tkinter.Entry(self.lframe_settings_a, textvariable=self.voltage_set_a_var, width=7, justify='right')
self.time_set_a_var = Tkinter.IntVar()
self.entry_time_set_a = Tkinter.Entry(self.lframe_settings_a, textvariable=self.time_set_a_var, width=7, justify='right')
self.delay_set_a_var = Tkinter.IntVar()
self.entry_delay_set_a = Tkinter.Entry(self.lframe_settings_a, textvariable=self.delay_set_a_var, width=7, justify='right')
self.repeat_set_a_var = Tkinter.IntVar()
self.entry_repeat_set_a = Tkinter.Entry(self.lframe_settings_a, textvariable=self.repeat_set_a_var, width=7, justify='right')
#B
self.voltage_range_b_var = Tkinter.IntVar()
self.spin_voltage_range_b = Tkinter.Spinbox(self.lframe_settings_b, textvariable=self.voltage_range_b_var, width=5,
from_=0, to=30, justify='right')
self.over_voltage_b_var = Tkinter.IntVar()
self.spin_over_voltage_b = Tkinter.Spinbox(self.lframe_settings_b, textvariable=self.over_voltage_b_var, width=5,
from_=0, to=30, justify='right')
self.heat_set_b_var = Tkinter.IntVar()
self.entry_heat_set_b = Tkinter.Entry(self.lframe_settings_b, textvariable=self.heat_set_b_var, width=7, justify='right')
self.meas_set_b_var = Tkinter.IntVar()
self.entry_meas_set_b = Tkinter.Entry(self.lframe_settings_b, textvariable=self.meas_set_b_var, width=7, justify='right')
self.voltage_set_b_var = Tkinter.IntVar()
self.entry_voltage_set_b = Tkinter.Entry(self.lframe_settings_b, textvariable=self.voltage_set_b_var, width=7, justify='right')
self.time_set_b_var = Tkinter.IntVar()
self.entry_time_set_b = Tkinter.Entry(self.lframe_settings_b, textvariable=self.time_set_b_var, width=7, justify='right')
self.delay_set_b_var = Tkinter.IntVar()
self.entry_delay_set_b = Tkinter.Entry(self.lframe_settings_b, textvariable=self.delay_set_b_var, width=7, justify='right')
self.repeat_set_b_var = Tkinter.IntVar()
self.entry_repeat_set_b = Tkinter.Entry(self.lframe_settings_b, textvariable=self.repeat_set_b_var, width=7, justify='right')
#C
self.voltage_range_c_var = Tkinter.IntVar()
self.spin_voltage_range_c = Tkinter.Spinbox(self.lframe_settings_c, textvariable=self.voltage_range_c_var, width=5,
from_=0, to=30, justify='right')
self.over_voltage_c_var = Tkinter.IntVar()
self.spin_over_voltage_c = Tkinter.Spinbox(self.lframe_settings_c, textvariable=self.over_voltage_c_var, width=5,
from_=0, to=30, justify='right')
self.heat_set_c_var = Tkinter.IntVar()
self.entry_heat_set_c = Tkinter.Entry(self.lframe_settings_c, textvariable=self.heat_set_c_var, width=7, justify='right')
self.meas_set_c_var = Tkinter.IntVar()
self.entry_meas_set_c = Tkinter.Entry(self.lframe_settings_c, textvariable=self.meas_set_c_var, width=7, justify='right')
self.voltage_set_c_var = Tkinter.IntVar()
self.entry_voltage_set_c = Tkinter.Entry(self.lframe_settings_c, textvariable=self.voltage_set_c_var, width=7, justify='right')
self.time_set_c_var = Tkinter.IntVar()
self.entry_time_set_c = Tkinter.Entry(self.lframe_settings_c, textvariable=self.time_set_c_var, width=7, justify='right')
self.delay_set_c_var = Tkinter.IntVar()
self.entry_delay_set_c = Tkinter.Entry(self.lframe_settings_c, textvariable=self.delay_set_c_var, width=7, justify='right')
self.repeat_set_c_var = Tkinter.IntVar()
self.entry_repeat_set_c = Tkinter.Entry(self.lframe_settings_c, textvariable=self.repeat_set_c_var, width=7, justify='right')
# Button
self.button_run = Tkinter.Button(self.frame_settings, text="Run", command=lambda: self.on_run(), width=25)
self.button_stop = Tkinter.Button(self.frame_settings, text="Stop", command=lambda: self.on_stop(), width=25)
self.button_quit = Tkinter.Button(self.frame_settings, text="Quit", command=lambda: self.on_quit(), width=25)
# Grid
parent.resizable(False, False)
parent.grid_columnconfigure(0, weight=0)
# Instrument #A
self.frame_instruments.grid(row=0, column=0)
self.lframe_instrumet_a.grid(row=0, column=0)
self.label_power_supply_a.grid(row=0, column=0, sticky='W')
self.label_multimeter_a.grid(row=1, column=0, sticky='W')
self.combo_power_supply_a.grid(row=0, column=1)
self.combo_multimeter_a.grid(row=1, column=1)
self.check_temp_sensor_a.grid(row=2, column=1)
self.lframe_settings_a.grid(row=0, column=2)
self.label_voltage_range_a.grid(row=0, column=2, sticky='W')
self.spin_voltage_range_a.grid(row=0, column=3)
self.label_over_voltage_a.grid(row=1, column=2, sticky='W')
self.label_heat_set_a.grid(row=2, column=2, sticky='W')
self.spin_over_voltage_a.grid(row=1, column=3)
self.entry_heat_set_a.grid(row=2, column=3)
self.label_voltage_set_a.grid(row=0, column=4, sticky='W')
self.label_meas_set_a.grid(row=1, column=4, sticky='W')
self.label_set_time_a.grid(row=2, column=4, sticky='W')
self.entry_voltage_set_a.grid(row=0, column=5)
self.entry_meas_set_a.grid(row=1, column=5)
self.entry_time_set_a.grid(row=2, column=5)
self.label_set_delay_a.grid(row=0, column=6, sticky='W')
self.label_set_repeat_a.grid(row=1, column=6, sticky='W')
self.entry_delay_set_a.grid(row=0, column=7)
self.entry_repeat_set_a.grid(row=1, column=7)
self.check_instrument_a.grid(row=2, column=6, sticky='W')
# Instrument #B
self.lframe_instrumet_b.grid(row=3)
self.label_power_supply_b.grid(row=3, column=0)
self.label_multimeter_b.grid(row=4, column=0)
self.combo_power_supply_b.grid(row=3, column=1)
self.combo_multimeter_b.grid(row=4, column=1)
self.check_temp_sensor_b.grid(row=5, column=1)
self.lframe_settings_b.grid(row=3, column=2)
self.label_voltage_range_b.grid(row=3, column=2, sticky='W')
self.spin_voltage_range_b.grid(row=3, column=3)
self.label_over_voltage_b.grid(row=4, column=2, sticky='W')
self.label_heat_set_b.grid(row=5, column=2, sticky='W')
self.spin_over_voltage_b.grid(row=4, column=3)
self.entry_heat_set_b.grid(row=5, column=3)
self.label_voltage_set_b.grid(row=3, column=4, sticky='W')
self.label_meas_set_b.grid(row=4, column=4, sticky='W')
self.label_set_time_b.grid(row=5, column=4, sticky='W')
self.entry_voltage_set_b.grid(row=3, column=5)
self.entry_meas_set_b.grid(row=4, column=5)
self.entry_time_set_b.grid(row=5, column=5)
self.label_set_delay_b.grid(row=3, column=6, sticky='W')
self.label_set_repeat_b.grid(row=4, column=6, sticky='W')
self.entry_delay_set_b.grid(row=3, column=7)
self.entry_repeat_set_b.grid(row=4, column=7)
self.check_instrument_b.grid(row=5, column=6, sticky='W')
# Instrument #C
self.lframe_instrumet_c.grid(row=6)
self.label_power_supply_c.grid(row=6, column=0)
self.label_multimeter_c.grid(row=7, column=0)
self.combo_power_supply_c.grid(row=6, column=1)
self.combo_multimeter_c.grid(row=7, column=1)
self.check_temp_sensor_c.grid(row=8, column=1)
self.lframe_settings_c.grid(row=6, column=2)
self.label_voltage_range_c.grid(row=6, column=2, sticky='W')
self.spin_voltage_range_c.grid(row=6, column=3)
self.label_over_voltage_c.grid(row=7, column=2, sticky='W')
self.label_heat_set_c.grid(row=8, column=2, sticky='W')
self.spin_over_voltage_c.grid(row=7, column=3)
self.entry_heat_set_c.grid(row=8, column=3)
self.label_voltage_set_c.grid(row=6, column=4, sticky='W')
self.label_meas_set_c.grid(row=7, column=4, sticky='W')
self.label_set_time_c.grid(row=8, column=4, sticky='W')
self.entry_voltage_set_c.grid(row=6, column=5)
self.entry_meas_set_c.grid(row=7, column=5)
self.entry_time_set_c.grid(row=8, column=5)
self.label_set_delay_c.grid(row=6, column=6, sticky='W')
self.label_set_repeat_c.grid(row=7, column=6, sticky='W')
self.entry_delay_set_c.grid(row=6, column=7)
self.entry_repeat_set_c.grid(row=7, column=7)
self.check_instrument_c.grid(row=8, column=6, sticky='W')
# Button
self.frame_settings.grid(row=8)
self.button_run.grid(row=8, column=0)
self.button_stop.grid(row=8,column=1)
self.button_quit.grid(row=8, column=2)
# Function
def about(self):
tkMessageBox.showinfo("About", "About" %chr(64))
def on_quit(self):
self.parent.quit()
self.parent.destroy()
self.fout.close()
def save_file(self):
self.file_opt = self.options = {}
self.options['filetypes'] = [('Text Files', '.txt')]
self.dataname = asksaveasfilename(**self.file_opt)
self.datamode = 'a'
try:
self.fout = open(self.dataname, self.datamode)
except Exception, e:
strError = "Output file open error: "+ str(e)
tkMessageBox.showerror("Error", strError)
def on_stop(self):
self.button_quit.configure(state='active')
def on_run(self):
self.button_quit.configure(state='disable')
create_header = Header(gui.fout, self.selected_instruments_query(),self.dataname, self.voltage_range_a_var.get(),
self.voltage_set_a_var.get(), self.delay_set_a_var.get(), self.over_voltage_a_var.get(),
self.meas_set_a_var.get(), self.repeat_set_a_var.get(), self.heat_set_a_var.get(),
self.temp_sensor_a_var.get(), self.voltage_range_b_var.get(),
self.voltage_set_b_var.get(), self.delay_set_b_var.get(), self.over_voltage_b_var.get(),
self.meas_set_b_var.get(), self.repeat_set_b_var.get(), self.heat_set_b_var.get(),
self.temp_sensor_b_var.get(),self.voltage_range_c_var.get(),
self.voltage_set_c_var.get(), self.delay_set_c_var.get(), self.over_voltage_c_var.get(),
self.meas_set_c_var.get(), self.repeat_set_c_var.get(), self.heat_set_c_var.get(),
self.temp_sensor_c_var.get())
def selected_instruments_query(self):
selected_power_query = [self.instrument_var_a.get(), self.instrument_var_b.get(), self.instrument_var_c.get()]
selected_multimeter_query = [self.temp_sensor_a_var.get(), self.temp_sensor_b_var.get(), self.temp_sensor_c_var.get()]
selected_instruments_query = [selected_power_query,selected_multimeter_query]
return selected_instruments_query
class Header:
WRITE = 0
def __init__(self,fout,selected_instruments,dataname,voltage_range_a_var,voltage_set_a_var, delay_set_a_var,
over_voltage_a_var,meas_set_a_var, repeat_set_a_var, heat_set_a_var, time_set_a_var, voltage_range_b_var,
voltage_set_b_var, delay_set_b_var,over_voltage_b_var,meas_set_b_var, repeat_set_b_var,
heat_set_b_var, time_set_b_var, voltage_range_c_var,voltage_set_c_var, delay_set_c_var,
over_voltage_c_var,meas_set_c_var, repeat_set_c_var, heat_set_c_var, time_set_c_var):
self.fout = fout
self.selected_instruments = selected_instruments
self.dataname = dataname
self.voltage_range_a_var = voltage_range_a_var
self.voltage_set_a_var = voltage_set_a_var
self.delay_set_a_var = delay_set_a_var
self.over_voltage_a_var = over_voltage_a_var
self.meas_set_a_var = meas_set_a_var
self.repeat_set_a_var = repeat_set_a_var
self.heat_set_a_var = heat_set_a_var
self.time_set_a_var = time_set_a_var
self.voltage_range_b_var = voltage_range_b_var
self.voltage_set_b_var = voltage_set_b_var
self.delay_set_b_var = delay_set_b_var
self.over_voltage_b_var = over_voltage_b_var
self.meas_set_b_var = meas_set_b_var
self.repeat_set_b_var = repeat_set_b_var
self.heat_set_b_var = heat_set_b_var
self.time_set_b_var = time_set_b_var
self.voltage_range_c_var = voltage_range_c_var
self.voltage_set_c_var = voltage_set_c_var
self.delay_set_c_var = delay_set_c_var
self.over_voltage_c_var = over_voltage_c_var
self.meas_set_c_var = meas_set_c_var
self.repeat_set_c_var = repeat_set_c_var
self.heat_set_c_var = heat_set_c_var
self.time_set_c_var = time_set_c_var
print self.selected_instruments
# Header involve data only once
if Header.WRITE == 0:
self.header_file()
Header.WRITE = 1
def header_file(self):
t = datetime.datetime.now()
curr_datetime = t.timetuple()
yr = str(curr_datetime[0])
curr_date = "%02d."%int(yr[2:]) + "%02d."%curr_datetime[1] + "%02d."%curr_datetime[2]
curr_time = "%02d:"%curr_datetime[3] + "%02d:"%curr_datetime[4] + "%02d"%curr_datetime[5]
time_data = curr_date + " " + curr_time
separate_line = "*"*120
str_out_time = "Filename: \t%s \nTime/Date: \t%s \n\nInstrument - #A\n\n" % (self.dataname, time_data)
self.fout.write(str_out_time)
str_out_a = "Voltage Range: \t%d\tSet Voltage: \t%d\tMeasurement Delay: \t%d\n" \
"OVP: \t\t%d\tMeas.Set: \t%d\tRepeat: \t\t%d\n" \
"Heat.Set: \t%d\tTime Limit: \t%d\n\n\n" % (self.voltage_range_a_var,
self.voltage_set_a_var, self.delay_set_a_var, self.over_voltage_a_var,
self.meas_set_a_var, self.repeat_set_a_var, self.heat_set_a_var,
self.time_set_a_var)
str_out_b = "Instrument - #B\n\nVoltage Range: \t%d\tSet Voltage: \t%d\tMeasurement Delay: \t%d\n" \
"OVP: \t\t%d\tMeas.Set: \t%d\tRepeat: \t\t%d\n" \
"Heat.Set: \t%d\tTime Limit: \t%d\n\n\n" % (self.voltage_range_b_var,
self.voltage_set_b_var, self.delay_set_b_var, self.over_voltage_b_var,
self.meas_set_b_var, self.repeat_set_b_var, self.heat_set_b_var,
self.time_set_b_var)
str_out_c = "Instrument - #C\n\nVoltage Range: \t%d\tSet Voltage: \t%d\tMeasurement Delay: \t%d\n" \
"OVP: \t\t%d\tMeas.Set: \t%d\tRepeat: \t\t%d\n" \
"Heat.Set: \t%d\tTime Limit: \t%d\n\n\n%s\n" % (self.voltage_range_c_var,
self.voltage_set_c_var, self.delay_set_c_var, self.over_voltage_c_var,
self.meas_set_c_var, self.repeat_set_c_var, self.heat_set_c_var,
self.time_set_c_var, separate_line)
# Print header file depending of the instruments
for condition, string in zip(self.selected_instruments[0], [str_out_a, str_out_b, str_out_c]):
if condition:
self.fout.write(string)
if __name__ == '__main__':
root = Tkinter.Tk()
gui = Interface(root)
root.mainloop()
A terrifyingly simplified example of how you can use (and toggle) three different loops, running in parallel, (in this case) printing three different words.
Using Tkinters's after() method, these loops can run inside the main loop:
from Tkinter import *
class MultiLoop:
def __init__(self):
self.master = Tk()
self.run1 = False
self.run2 = False
self.run3 = False
button1 = Button(text="Toggle Monkey", command = self.togglemonkey).pack()
button2 = Button(text="Toggle eats", command = self.toggleeats).pack()
button3 = Button(text="Toggle banana", command = self.togglebanana).pack()
# first call:
self.master.after(0, self.loop1)
self.master.after(0, self.loop2)
self.master.after(0, self.loop3)
self.master.mainloop()
# The three loops
def loop1(self):
if self.run1 == True:
print("Monkey")
else:
pass
# schedule next run
self.master.after(100, self.loop1)
def loop2(self):
if self.run2 == True:
print("eats")
else:
pass
# schedule next run
self.master.after(1000, self.loop2)
def loop3(self):
if self.run3 == True:
print("banana")
else:
pass
# schedule next run
self.master.after(2000, self.loop3)
# The toggle functions
def togglemonkey(self):
self.run1 = True if self.run1 == False else False
def toggleeats(self):
self.run2 = True if self.run2 == False else False
def togglebanana(self):
self.run3 = True if self.run3 == False else False
MultiLoop()

python: Changing the content of a frame

I started a project where I want to script an application for my company to capture values of an iterative signal processing job.
I want to include the option to switch between different modules that require different parameters to test.
When I click on the buttons on the left I want the content of the data entry frame to change to a different set of Labels and Entry widgets. I tried to put the widgets for 'AAA' in a different class but I don't know how to initialize the class via button click so the widgets in the class get created/visible. I tried it with .lift() but that's ugly. I also want to keep the same 2 frames under the data entry frame, and the ScrolledText on the right, just working with the active module. Any ideas? Someone can push me in the right direction?
Oh yeah, and this is my first project apart from simple read->replace string-> scripts.
Here's the code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import Tkinter as tk
import json
import tkFileDialog
import sys
import ScrolledText
from Tkinter import*
class testlogger(tk.Tk):
def __init__(self,parent):
tk.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
#--------------------------------------------------------------------------------------
menubar = tk.Menu(self)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New")
filemenu.add_command(label="Open", command=self.load_file)
filemenu.add_command(label="Save", command=self.safe_file)
filemenu.add_command(label="Save as...")
filemenu.add_command(label="Close")
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = tk.Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo")
editmenu.add_separator()
editmenu.add_command(label="Cut")
editmenu.add_command(label="Copy")
editmenu.add_command(label="Paste")
editmenu.add_command(label="Delete")
editmenu.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index")
helpmenu.add_command(label="About...")
menubar.add_cascade(label="Help", menu=helpmenu)
self.config(menu=menubar)
#--------------------------------------------------------------------------------------
treeFrame = tk.Frame(self)
treeFrame.grid(column=0, row=1, sticky='NW')
b1 = Button(treeFrame, text=u'AAA', command=self.AAAlift)
b1.pack(fill='x')
b2 = Button(treeFrame, text=u'RADON', command=self.radonlift)
b2.pack(fill='x')
b3 = Button(treeFrame, text=u'Adaptive Subtract')
b3.pack(fill='x')
b4 = Button(treeFrame, text=u'GMP')
b4.pack(fill='x')
#--------------------------------------------------------------------------------------
#
#
#
#--------------------------------------------------------------------------------------
self.enterData = tk.LabelFrame(self, text=" Data Entry ")
self.enterData.grid(column=1, row=1, columnspan=4, sticky='NW', \
padx=5, pady=5, ipadx=5, ipady=5)
titleAAA = tk.Label(self.enterData, text="AAA")
titleAAA.grid(row=1, columnspan=4, sticky='N', padx=5, pady=2)
self.freqInput = tk.StringVar()
self.freqInput2 = tk.StringVar()
self.thresInput = tk.StringVar()
self.widthInput = tk.StringVar()
self.minFreq = tk.Label(self.enterData, text="Minimum Frequency")
self.minFreq.grid(row=2, column=1, sticky='E', padx=5, pady=2)
minFreqData = tk.Entry(self.enterData, textvariable=self.freqInput)
minFreqData.grid(row=2, column=2, sticky='E', padx=5, pady=2)
self.maxFreq = tk.Label(self.enterData, text="Maximum Frequency")
self.maxFreq.grid(row=3, column=1, sticky='E', padx=5, pady=2)
maxFreqData = tk.Entry(self.enterData, textvariable=self.freqInput2)
maxFreqData.grid(row=3, column=2, sticky='E', padx=5, pady=2)
self.threshold = tk.Label(self.enterData, text="Threshold")
self.threshold.grid(row=2, column=3, sticky='E', padx=5, pady=2)
thresData = tk.Entry(self.enterData, textvariable=self.thresInput)
thresData.grid(row=2, column=4, sticky='E', padx=5, pady=2)
self.width = tk.Label(self.enterData, text="SpatialWidth")
self.width.grid(row=3, column=3, sticky='E', padx=5, pady=2)
widthData = tk.Entry(self.enterData, textvariable=self.widthInput)
widthData.grid(row=3, column=4, sticky='E', padx=5, pady=2)
self.valueList = [self.freqInput, self.freqInput2, self.thresInput, self.widthInput]
self.labelList = [self.minFreq, self.maxFreq, self.threshold, self.width]
enteredAAAData = []
#--------------------------------------------------------------------------------------
self.radon = LabelFrame(self, text=" Data Entry ")
self.radon.grid(column=1, row=1, columnspan=4, sticky='NW', \
padx=5, pady=5, ipadx=5, ipady=5)
titleRadon = Label(self.radon, text="Radon Fwd Transform")
titleRadon.grid(row=1, columnspan=4, sticky='N', padx=5, pady=2)
self.minMOInput = StringVar()
self.maxMOInput = StringVar()
self.offsetInput = StringVar()
self.numpInput = StringVar()
self.motypeInput = StringVar()
self.maxfreqInput = StringVar()
self.minMO = Label(self.radon, text="Minimum Moveout")
self.minMO.grid(row=2, column=1, sticky='E', padx=5, pady=2)
minMOData = Entry(self.radon, textvariable=self.minMOInput)
minMOData.grid(row=2, column=2, sticky='E', padx=5, pady=2)
self.maxMO = Label(self.radon, text="Maximum Moveout")
self.maxFreq.grid(row=3, column=1, sticky='E', padx=5, pady=2)
maxMOData = Entry(self.radon, textvariable=self.maxMOInput)
maxMOData.grid(row=3, column=2, sticky='E', padx=5, pady=2)
self.offset = Label(self.radon, text="Reference Offset")
self.offset.grid(row=2, column=3, sticky='E', padx=5, pady=2)
offsetData = Entry(self.radon, textvariable=self.offsetInput)
offsetData.grid(row=2, column=4, sticky='E', padx=5, pady=2)
self.numP = Label(self.radon, text="Number of P-Traces")
self.numP.grid(row=3, column=3, sticky='E', padx=5, pady=2)
numPData = Entry(self.radon, textvariable=self.numpInput)
numPData.grid(row=3, column=4, sticky='E', padx=5, pady=2)
self.motype = Label(self.radon, text="Moveout Type")
self.motype.grid(row=4, column=1, sticky='E', padx=5, pady=2)
motypeData = Entry(self.radon, textvariable=self.motypeInput)
motypeData.grid(row=4, column=2, sticky='E', padx=5, pady=2)
self.maxfreq = Label(self.radon, text="Maximum Frequency")
self.maxfreq.grid(row=4, column=3, sticky='E', padx=5, pady=2)
maxfreqData = Entry(self.radon, textvariable=self.maxfreqInput)
maxfreqData.grid(row=4, column=4, sticky='E', padx=5, pady=2)
self.valueList = [self.minMOInput, self.maxMOInput, self.offsetInput, self.numpInput, self.motypeInput, self.maxfreqInput]
self.labelList = [self.minMO, self.maxMO, self.offset, self.numP, self.motype, self.maxfreq]
enteredRadonData = []
#--------------------------------------------------------------------------------------
evalData = tk.Frame(self)
evalData.grid(column=1, row=2, sticky='NW', \
padx=5, pady=5, ipadx=5, ipady=5)
evalLabel = tk.Label(evalData, text="Evaluation")
evalLabel.grid(row=1, column=1, columnspan=3, sticky='N', padx=5, pady=2)
self.eval_state = tk.StringVar()
goodRadio = tk.Radiobutton(evalData, text="Good", variable=self.eval_state, value='Good')
goodRadio.grid(row=2, column=1, sticky='W', padx=5, pady=2)
badRadio = tk.Radiobutton(evalData, text="Bad", variable=self.eval_state, value='Bad')
badRadio.grid(row=2, column=2, sticky='W', padx=5, pady=2)
sameRadio = tk.Radiobutton(evalData, text="Same", variable=self.eval_state, value='Same')
sameRadio.grid(row=2, column=3, sticky='W', padx=5, pady=2)
qcDisp = tk.Label(evalData, text="QC Displays:")
qcDisp.grid(row=2,column=4, sticky='W', padx=10, pady=2)
self.checkB4 = tk.IntVar()
optionBefore = tk.Checkbutton(evalData, text="Before", variable=self.checkB4, onvalue=1, offvalue=0)
optionBefore.grid(row=1, column=5, sticky='W', padx=5, pady=2)
optionAfter = tk.Checkbutton(evalData, text="After", onvalue=1, offvalue=0)
optionAfter.grid(row=2, column=5, sticky='W', padx=5, pady=2)
optionDiff = tk.Checkbutton(evalData, text="Difference", onvalue=1, offvalue=0)
optionDiff.grid(row=3, column=5, sticky='W', padx=5, pady=2)
optionSpectrum = tk.Checkbutton(evalData, text="Frequency Spectrum", onvalue=1, offvalue=0)
optionSpectrum.grid(row=1, column=6, sticky='W', padx=5, pady=2)
optionAuto = tk.Checkbutton(evalData, text="Auto Correlation", onvalue=1, offvalue=0)
optionAuto.grid(row=2, column=6, sticky='W', padx=5, pady=2)
optionBanana = tk.Checkbutton(evalData, text="I'm a Banana", onvalue=1, offvalue=0)
optionBanana.grid(row=3, column=6, sticky='W', padx=5, pady=2)
#--------------------------------------------------------------------------------------
self.comment = tk.Text(self, height=5, bg='white')
self.comment.grid(column=1, row=3, sticky='NW', \
padx=5, pady=5, ipadx=5, ipady=5)
submit_b = tk.Button(self, text=u"Submit", command=self.enter_data)
submit_b.grid(column=1, row=4, sticky='NE')
#--------------------------------------------------------------------------------------
protocolFrame = tk.LabelFrame(self, text="Protocol")
protocolFrame.grid(row=1, column=2, rowspan=3, sticky='NW')
self.protocolText = ScrolledText.ScrolledText(protocolFrame,state='disabled',height=30, width=70)
self.protocolText.grid(column=0, row=0, sticky='NE')
#--------------------------------------------------------------------------------------
self.L = []
#--------------------------------------------------------------------------------------
def enter_data(self):
x = self.labelList[0].cget('text')
y = self.valueList[0].get()
self.L.append(x + ': ' + y)
x = self.labelList[1].cget('text')
y = self.valueList[1].get()
self.L.append(x + ': ' + y)
x = self.labelList[2].cget('text')
y = self.valueList[2].get()
self.L.append(x + ': ' + y)
x = self.labelList[3].cget('text')
y = self.valueList[3].get()
self.L.append(x + ': ' + y)
x = self.eval_state.get()
self.L.append(x)
if self.checkB4 == 1:
y = self.optionBefore.cget('text')
self.L.append(y)
x = self.comment.get('1.0','end')
self.L.append(x)
self.L.append('-------------------------------------\n')
self.protocolText.config(state='normal')
self.protocolText.insert(tk.END, '\n'.join(self.L))
self.protocolText.config(state='disabled')
self.L = []
#------------------------------------------------------------------------------------------
def safe_file(self):
s = self.protocolText.get('1.0','end')
with open('my_json', 'w') as fp:
json.dump(s, fp)
def load_file(self):
options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
options['initialdir'] = '/home'
options['parent'] = self.parent
options['title'] = "Open a file"
self.protocolText.config(state='normal')
with tkFileDialog.askopenfile(mode='r', **options) as f_handle:
for line in f_handle:
self.protocolText.insert(tk.END, f_handle)
self.protocolText.config(state='disabled')
def AAAlift(self):
self.enterData.lift()
def radonlift(self):
self.radon.lift()
if __name__ == "__main__":
app = testlogger(None)
app.title('Testlogger')
app.mainloop()
When app starts:
When AAA is pressed:
I modified your code slightly. Basically I added containerFrame, to wrap the LabelFrames. I think its easier to make it easer this way. I also added some padding in other places to make the Protocol part inline with others.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import Tkinter as tk
import json
import tkFileDialog
import sys
import ScrolledText
from Tkinter import*
class testlogger(tk.Tk):
def __init__(self,parent):
tk.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
#--------------------------------------------------------------------------------------
menubar = tk.Menu(self)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New")
filemenu.add_command(label="Open", command=self.load_file)
filemenu.add_command(label="Save", command=self.safe_file)
filemenu.add_command(label="Save as...")
filemenu.add_command(label="Close")
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = tk.Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo")
editmenu.add_separator()
editmenu.add_command(label="Cut")
editmenu.add_command(label="Copy")
editmenu.add_command(label="Paste")
editmenu.add_command(label="Delete")
editmenu.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index")
helpmenu.add_command(label="About...")
menubar.add_cascade(label="Help", menu=helpmenu)
self.config(menu=menubar)
#--------------------------------------------------------------------------------------
treeFrame = tk.Frame(self)
treeFrame.grid(column=0, row=1, sticky='NW')
b1 = Button(treeFrame, text=u'AAA', command=self.AAAlift)
b1.pack(fill='x')
b2 = Button(treeFrame, text=u'RADON', command=self.radonlift)
b2.pack(fill='x')
b3 = Button(treeFrame, text=u'Adaptive Subtract')
b3.pack(fill='x')
b4 = Button(treeFrame, text=u'GMP')
b4.pack(fill='x')
#--------------------------------------------------------------------------------------
#
#
#
#--------------------------------------------------------------------------------------
self.containerFrame = tk.Frame(self)
self.containerFrame.grid(column=1, row=1, columnspan=4, sticky='NW', \
padx=5, pady=5, ipadx=1, ipady=1)
self.enterData = tk.LabelFrame(self.containerFrame, text=" Data Entry ")
#self.enterData.pack(fill=tk.BOTH, expand=1)
self.enterData.grid(column=0, row=0, sticky='NW', ipadx=17)
# self.enterData.grid(column=1, row=1, columnspan=4, sticky='NW', \
# padx=5, pady=5, ipadx=5, ipady=5)
titleAAA = tk.Label(self.enterData, text="AAA")
titleAAA.grid(row=1, columnspan=4, sticky='N', padx=5, pady=2)
self.freqInput = tk.StringVar()
self.freqInput2 = tk.StringVar()
self.thresInput = tk.StringVar()
self.widthInput = tk.StringVar()
self.minFreq = tk.Label(self.enterData, text="Minimum Frequency")
self.minFreq.grid(row=2, column=1, sticky='E', padx=5, pady=2)
minFreqData = tk.Entry(self.enterData, textvariable=self.freqInput)
minFreqData.grid(row=2, column=2, sticky='E', padx=5, pady=2)
self.maxFreq = tk.Label(self.enterData, text="Maximum Frequency")
self.maxFreq.grid(row=3, column=1, sticky='E', padx=5, pady=2)
maxFreqData = tk.Entry(self.enterData, textvariable=self.freqInput2)
maxFreqData.grid(row=3, column=2, sticky='E', padx=5, pady=2)
self.threshold = tk.Label(self.enterData, text="Threshold")
self.threshold.grid(row=2, column=3, sticky='E', padx=5, pady=2)
thresData = tk.Entry(self.enterData, textvariable=self.thresInput)
thresData.grid(row=2, column=4, sticky='E', padx=5, pady=2)
self.width = tk.Label(self.enterData, text="SpatialWidth")
self.width.grid(row=3, column=3, sticky='E', padx=5, pady=2)
widthData = tk.Entry(self.enterData, textvariable=self.widthInput)
widthData.grid(row=3, column=4, sticky='E', padx=5, pady=2)
self.valueList = [self.freqInput, self.freqInput2, self.thresInput, self.widthInput]
self.labelList = [self.minFreq, self.maxFreq, self.threshold, self.width]
enteredAAAData = []
#--------------------------------------------------------------------------------------
self.radon = LabelFrame(self.containerFrame, text=" Data Entry ")
#self.radon.pack(fill=tk.BOTH, expand=1)
self.radon.grid(column=0, row=0, sticky='NW', ipadx=0)
titleRadon = Label(self.radon, text="Radon Fwd Transform")
titleRadon.grid(row=1, columnspan=4, sticky='N', padx=5, pady=2)
self.minMOInput = StringVar()
self.maxMOInput = StringVar()
self.offsetInput = StringVar()
self.numpInput = StringVar()
self.motypeInput = StringVar()
self.maxfreqInput = StringVar()
self.minMO = Label(self.radon, text="Minimum Moveout")
self.minMO.grid(row=2, column=1, sticky='E', padx=5, pady=2)
minMOData = Entry(self.radon, textvariable=self.minMOInput)
minMOData.grid(row=2, column=2, sticky='E', padx=5, pady=2)
self.maxMO = Label(self.radon, text="Maximum Moveout")
self.maxFreq.grid(row=3, column=1, sticky='E', padx=5, pady=2)
maxMOData = Entry(self.radon, textvariable=self.maxMOInput)
maxMOData.grid(row=3, column=2, sticky='E', padx=5, pady=2)
self.offset = Label(self.radon, text="Reference Offset")
self.offset.grid(row=2, column=3, sticky='E', padx=5, pady=2)
offsetData = Entry(self.radon, textvariable=self.offsetInput)
offsetData.grid(row=2, column=4, sticky='E', padx=5, pady=2)
self.numP = Label(self.radon, text="Number of P-Traces")
self.numP.grid(row=3, column=3, sticky='E', padx=5, pady=2)
numPData = Entry(self.radon, textvariable=self.numpInput)
numPData.grid(row=3, column=4, sticky='E', padx=5, pady=2)
self.motype = Label(self.radon, text="Moveout Type")
self.motype.grid(row=4, column=1, sticky='E', padx=5, pady=2)
motypeData = Entry(self.radon, textvariable=self.motypeInput)
motypeData.grid(row=4, column=2, sticky='E', padx=5, pady=2)
self.maxfreq = Label(self.radon, text="Maximum Frequency")
self.maxfreq.grid(row=4, column=3, sticky='E', padx=5, pady=2)
maxfreqData = Entry(self.radon, textvariable=self.maxfreqInput)
maxfreqData.grid(row=4, column=4, sticky='E', padx=5, pady=2)
self.valueList = [self.minMOInput, self.maxMOInput, self.offsetInput, self.numpInput, self.motypeInput, self.maxfreqInput]
self.labelList = [self.minMO, self.maxMO, self.offset, self.numP, self.motype, self.maxfreq]
enteredRadonData = []
#--------------------------------------------------------------------------------------
evalData = tk.Frame(self)
evalData.grid(column=1, row=2, sticky='NW', \
padx=5, pady=5, ipadx=5, ipady=5)
evalLabel = tk.Label(evalData, text="Evaluation")
evalLabel.grid(row=1, column=1, columnspan=3, sticky='N', padx=5, pady=2)
self.eval_state = tk.StringVar()
goodRadio = tk.Radiobutton(evalData, text="Good", variable=self.eval_state, value='Good')
goodRadio.grid(row=2, column=1, sticky='W', padx=5, pady=2)
badRadio = tk.Radiobutton(evalData, text="Bad", variable=self.eval_state, value='Bad')
badRadio.grid(row=2, column=2, sticky='W', padx=5, pady=2)
sameRadio = tk.Radiobutton(evalData, text="Same", variable=self.eval_state, value='Same')
sameRadio.grid(row=2, column=3, sticky='W', padx=5, pady=2)
qcDisp = tk.Label(evalData, text="QC Displays:")
qcDisp.grid(row=2,column=4, sticky='W', padx=10, pady=2)
self.checkB4 = tk.IntVar()
optionBefore = tk.Checkbutton(evalData, text="Before", variable=self.checkB4, onvalue=1, offvalue=0)
optionBefore.grid(row=1, column=5, sticky='W', padx=5, pady=2)
optionAfter = tk.Checkbutton(evalData, text="After", onvalue=1, offvalue=0)
optionAfter.grid(row=2, column=5, sticky='W', padx=5, pady=2)
optionDiff = tk.Checkbutton(evalData, text="Difference", onvalue=1, offvalue=0)
optionDiff.grid(row=3, column=5, sticky='W', padx=5, pady=2)
optionSpectrum = tk.Checkbutton(evalData, text="Frequency Spectrum", onvalue=1, offvalue=0)
optionSpectrum.grid(row=1, column=6, sticky='W', padx=5, pady=2)
optionAuto = tk.Checkbutton(evalData, text="Auto Correlation", onvalue=1, offvalue=0)
optionAuto.grid(row=2, column=6, sticky='W', padx=5, pady=2)
optionBanana = tk.Checkbutton(evalData, text="I'm a Banana", onvalue=1, offvalue=0)
optionBanana.grid(row=3, column=6, sticky='W', padx=5, pady=2)
#--------------------------------------------------------------------------------------
self.comment = tk.Text(self, height=5, bg='white')
self.comment.grid(column=1, row=3, sticky='NW', \
padx=5, pady=5, ipadx=5, ipady=5)
submit_b = tk.Button(self, text=u"Submit", command=self.enter_data)
submit_b.grid(column=1, row=4, sticky='NE')
#--------------------------------------------------------------------------------------
protocolFrame = tk.LabelFrame(self, text="Protocol")
protocolFrame.grid(row=1, column=2, padx=45, pady=5, rowspan=3, sticky='NW')
self.protocolText = ScrolledText.ScrolledText(protocolFrame,state='disabled',height=30, width=70)
self.protocolText.grid(column=0, row=0, sticky='NE')
#--------------------------------------------------------------------------------------
self.L = []
#--------------------------------------------------------------------------------------
def enter_data(self):
x = self.labelList[0].cget('text')
y = self.valueList[0].get()
self.L.append(x + ': ' + y)
x = self.labelList[1].cget('text')
y = self.valueList[1].get()
self.L.append(x + ': ' + y)
x = self.labelList[2].cget('text')
y = self.valueList[2].get()
self.L.append(x + ': ' + y)
x = self.labelList[3].cget('text')
y = self.valueList[3].get()
self.L.append(x + ': ' + y)
x = self.eval_state.get()
self.L.append(x)
if self.checkB4 == 1:
y = self.optionBefore.cget('text')
self.L.append(y)
x = self.comment.get('1.0','end')
self.L.append(x)
self.L.append('-------------------------------------\n')
self.protocolText.config(state='normal')
self.protocolText.insert(tk.END, '\n'.join(self.L))
self.protocolText.config(state='disabled')
self.L = []
#------------------------------------------------------------------------------------------
def safe_file(self):
s = self.protocolText.get('1.0','end')
with open('my_json', 'w') as fp:
json.dump(s, fp)
def load_file(self):
options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
options['initialdir'] = '/home'
options['parent'] = self.parent
options['title'] = "Open a file"
self.protocolText.config(state='normal')
with tkFileDialog.askopenfile(mode='r', **options) as f_handle:
for line in f_handle:
self.protocolText.insert(tk.END, f_handle)
self.protocolText.config(state='disabled')
def AAAlift(self):
#self.enterData.grid_forget()
self.radon.grid_remove()
self.enterData.grid()
def radonlift(self):
self.enterData.grid_remove()
self.radon.grid()
if __name__ == "__main__":
app = testlogger(None)
app.title('Testlogger')
app.mainloop()
The screenshots are:
Obviously more work is needed to make everything "even" and inline with each other, but pressing AAA and RADON buttons works as expected (I think). You can expand/amend on my modifications, and hopefully it will allow you to achieve desired effect.

Using Python and TKinter, how do I redraw the main screen

I have a program where the main window is divided into two sections each section has a collection of forms (simple label/input columns). The default is 4 of these columns in the first section and 2 in the second section. I would like the user to be able to change this ratio. I think I have all of the programming in place to do this, I just can't get the main window to redraw with the correct structure. Any help would be much appreciated. Thanks.
I like the simplicity and idea behind your example, however, I'm modifying some legacy code and don't have the time to rewrite my layouts as definitions. I tried to create a def that would simply do grid_columnconfig(), but that didn't work. I've reduced the code so that it looks like what I'm working with and it is also functional. If you change the variable 'max_pol_modules' it adjusts columns on the left versus columns on the right, so, I'm trying to change this variable through an interface widget and redraw.
from Tkinter import *
import tkFont
max_pol_modules = 3
max_bus_modules = 6 - max_pol_modules
tech_green = '#5E9732'
button_grey = '#666666'
grey = '#777777'
def config1():
global max_pol_modules, max_bus_modules
max_pol_modules = 1
max_bus_modules = 6 - max_pol_modules
# print max_bus_modules
# left_frame.update()
def config2():
global max_pol_modules, max_bus_modules
max_pol_modules = 2
max_bus_modules = 6 - max_pol_modules
# print max_bus_modules
def config3():
global max_pol_modules, max_bus_modules
max_pol_modules = 3
max_bus_modules = 6 - max_pol_modules
# print max_bus_modules
def config4():
global max_pol_modules, max_bus_modules
max_pol_modules = 4
max_bus_modules = 6 - max_pol_modules
# print max_bus_modules
def about():
box.showinfo("About GUI","GE Bus Converter and Point of Load GUI")
def bar(frame, row, span):
"create a bar to separate a section"
x = Frame(frame, relief=GROOVE, bd=2, width=86*(span+1), height=2)
x.grid(row=row, column=0, columnspan=10, pady=7, sticky=S+E)
x.grid_propagate(0)
def bar2(frame, row, span):
"create a bar to separate a section"
x = Frame(frame, relief=GROOVE, bd=2, width=86*(span+1), height=2)
x.grid(row=row, column=0, columnspan=10, pady=3, sticky=S+E)
x.grid_propagate(0)
def bar3(frame, row, span):
"create a bar to separate a section"
x = Frame(frame, relief=GROOVE, bd=2, width=100, height=2)
x.grid(row=row, column=0, columnspan=10, pady=7, sticky=S+E)
x.grid_propagate(0)
root = Tk()
menubar = Menu(root)
submenu=Menu(menubar,tearoff=0)
submenu2=Menu(submenu,tearoff=0)
submenu2.add_command(label="1 - 5", command=config1)
submenu2.add_command(label="2 - 4", command=config2)
submenu2.add_command(label="3 - 3", command=config3)
submenu2.add_command(label="4 - 2", command=config4)
submenu_help = Menu(submenu,tearoff=0)
submenu_help.add_command(label="About",command=about)
submenu.add_cascade(label="Change Configuration",menu=submenu2)
submenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="Settings",menu=submenu)
menubar.add_cascade(label="Help", menu=submenu_help)
# display the menu
root.config(menu=menubar)
entry_wid = 6
small_font = tkFont.Font(family='Arial', size=8, weight='bold')
lite_font = tkFont.Font(family='Arial', size=9)
large_font = tkFont.Font(family='Arial', size=9)
heading_font = tkFont.Font(family='Arial', size=10, weight='bold')
button_font = tkFont.Font(family='Arial', size=8, weight='bold')
root.option_add('*font', lite_font)
root.option_add('*background', '#C2C2C4')
root.option_add('*Label.font', small_font)
root.option_add('*Entry.background', 'white')
root.option_add('*Button.font', button_font)
root.option_add('*Button.background', button_grey)
root.option_add('*Button.foreground', 'yellow')
root.option_add('*Text.background', 'white')
root.option_add('*Text.font', small_font)
root.option_add('*ScrolledText.font', lite_font)
left_frame = Frame(root)
right_frame = Frame(root)
pol_frame = Frame(left_frame, bd=2, relief=SUNKEN)
x = Label(pol_frame, text="POL Address", anchor=E)
x.grid(row=0, column=0, sticky=E)
x = Label(pol_frame, text="Rtrim (Kohms)", anchor=E)
x.grid(row=1, column=0, sticky=E)
x = Label(pol_frame, text="Nominal Vout (V)", anchor=E)
x.grid(row=2, column=0, sticky=E)
bar2(pol_frame, 0, max_pol_modules)
module_address = []
module_i2c = []
module_status = []
module_resistor = []
module_vout_nominal = []
for i in range(max_pol_modules):
# Module ID and address
f = Frame(pol_frame)
x = Label(f, text=i+1)
x.grid(row=0, column=0)
v = StringVar()
x = Entry(f, textvariable=v, width=3, justify=CENTER)
x.grid(row=0, column=1)
f.grid(row=0, column=i+1, pady=8, padx=20)
module_address.append(v)
module_i2c.append("")
module_status.append(0)
# module resistor
v = StringVar()
x = Entry(pol_frame, textvariable=v, width=entry_wid, justify=CENTER)
f = lambda event, module=i: change_resistor_event(event, module)
g = lambda value, m=i, o=16: set_change(value, m, o)
x.bind("<KeyRelease>", f, "+")
x.bind("<KeyRelease>", g, "+")
x.bind("<FocusOut>", f, "+")
x.grid(row=1, column=i+1, pady=0)
module_resistor.append(v)
# module nominal vout
v = StringVar()
x = Label(pol_frame, textvariable=v, width=entry_wid-1,
relief=SUNKEN, bg='#DDDDDD', font=lite_font)
x.grid(row=2, column=i+1, pady=0)
module_vout_nominal.append(v)
bus_frame = Frame(left_frame, bd=2, relief=SUNKEN)
#x = Label(bus_frame, text="Module (address)", anchor=E)
#x.grid(row=0, column=max_pol_modules+1, sticky=E)
x = Label(bus_frame, text="Bus Conv Address", anchor=E)
x.grid(row=0, column=0, sticky=E)
config_bus = []
r = 0
#for i in range(max_pol_modules,max_pol_modules+max_bus_modules):
for i in range(max_bus_modules):
# Module ID and address
f = Frame(bus_frame)
x = Label(f, text=i+5)
x.grid(row=0, column=0)
v = StringVar()
x = Entry(f, textvariable=v, width=3, justify=CENTER)
x.grid(row=0, column=1)
f.grid(row=0, column=i+2, pady=8, padx=20)
module_address.append(v)
module_i2c.append("")
module_status.append(0)
bar2(bus_frame, r, max_bus_modules)
r += 1
# the measured values
measure_info = ["Vout (V)", "Iout (A)", "Vin (V)", "Temp (degC)"]
measures_bus = []
for mi in measure_info:
x = Label(bus_frame, text=mi, anchor=E)
x.grid(row=r, column=0, sticky=E)
m = []
for j in range(max_bus_modules):
v = StringVar()
x = Label(bus_frame, textvariable=v, width=entry_wid-1,
relief=SUNKEN, bg='#DDDDDD', font=lite_font)
x.grid(row=r, column=j+2)
m.append(v)
measures_bus.append(m)
r += 1
pol_frame.grid(row=0, column=0, sticky=N+W)
bus_frame.grid(row=0, column=1, sticky=N+W)
left_frame.grid(row=0, column=0, sticky=N)
right_frame.grid(row=0, column=1, sticky=N)
root.mainloop()
Edited Example where form[4] and form[5] need to be deleted.
import Tkinter as tk
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.forms = []
self.toolbar = tk.Frame(self)
self.toolbar.pack(side="top", fill="x", expand=False)
button2 = tk.Button(self.toolbar, text="2 columns", command=self.layout2col)
button3 = tk.Button(self.toolbar, text="3 columns", command=self.layout3col)
button2.pack(side="left")
button3.pack(side="left")
self.forms_frame = tk.Frame(self, borderwidth=2, relief="groove")
self.forms_frame.pack(side="top", fill="both", expand="True", padx=2, pady=2)
for i in range(6):
frame = tk.LabelFrame(self.forms_frame, text="Form %s" % i)
self.forms.append(frame)
label = tk.Label(frame, text="Field %s" % i)
entry = tk.Entry(frame, width=20)
label.pack(side="left", fill="y")
entry.pack(side="left", fill="both", expand=True)
self.layout2col()
def layout3col(self):
self.forms[0].grid(column=0, row=0, padx=4, pady=2, sticky="ew")
self.forms[1].grid(column=0, row=1, padx=4, pady=2, sticky="ew")
self.forms[2].grid(column=1, row=0, padx=4, pady=2, sticky="ew")
self.forms[3].grid(column=1, row=1, padx=4, pady=2, sticky="ew")
self.forms[4].grid(column=2, row=0, padx=4, pady=2, sticky="ew")
self.forms[5].grid(column=2, row=1, padx=4, pady=2, sticky="ew")
self.forms_frame.grid_columnconfigure(0, weight=1)
self.forms_frame.grid_columnconfigure(1, weight=1)
self.forms_frame.grid_columnconfigure(2, weight=1)
def layout2col(self):
self.forms[0].grid(column=0, row=0, padx=4, pady=2, sticky="ew")
self.forms[1].grid(column=0, row=1, padx=4, pady=2, sticky="ew")
self.forms[2].grid(column=1, row=0, padx=4, pady=2, sticky="ew")
self.forms[3].grid(column=1, row=1, padx=4, pady=2, sticky="ew")
self.forms_frame.grid_columnconfigure(0, weight=1)
self.forms_frame.grid_columnconfigure(1, weight=1)
self.forms_frame.grid_columnconfigure(2, weight=0)
if __name__ == "__main__":
app = App()
app.mainloop()
Since you are using the grid geometry manager, you just need to use the grid method to place them in their new rows and columns. You may need to also call rowconfigure and/or columnconfigure to attach appropriate weights to the new rows and columns.
Here's a bit of a contrived example showing the general principle. It could be more efficient but hopefully it gives you a rough idea:
import Tkinter as tk
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.forms = []
self.toolbar = tk.Frame(self)
self.toolbar.pack(side="top", fill="x", expand=False)
button2 = tk.Button(self.toolbar, text="2 columns", command=self.layout2col)
button3 = tk.Button(self.toolbar, text="3 columns", command=self.layout3col)
button2.pack(side="left")
button3.pack(side="left")
self.forms_frame = tk.Frame(self, borderwidth=2, relief="groove")
self.forms_frame.pack(side="top", fill="both", expand="True", padx=2, pady=2)
for i in range(6):
frame = tk.LabelFrame(self.forms_frame, text="Form %s" % i)
self.forms.append(frame)
label = tk.Label(frame, text="Field %s" % i)
entry = tk.Entry(frame, width=20)
label.pack(side="left", fill="y")
entry.pack(side="left", fill="both", expand=True)
self.layout2col()
def layout3col(self):
self.forms[0].grid(column=0, row=0, padx=4, pady=2, sticky="ew")
self.forms[1].grid(column=0, row=1, padx=4, pady=2, sticky="ew")
self.forms[2].grid(column=1, row=0, padx=4, pady=2, sticky="ew")
self.forms[3].grid(column=1, row=1, padx=4, pady=2, sticky="ew")
self.forms[4].grid(column=2, row=0, padx=4, pady=2, sticky="ew")
self.forms[5].grid(column=2, row=1, padx=4, pady=2, sticky="ew")
self.forms_frame.grid_columnconfigure(0, weight=1)
self.forms_frame.grid_columnconfigure(1, weight=1)
self.forms_frame.grid_columnconfigure(2, weight=1)
def layout2col(self):
self.forms[0].grid(column=0, row=0, padx=4, pady=2, sticky="ew")
self.forms[1].grid(column=0, row=1, padx=4, pady=2, sticky="ew")
self.forms[2].grid(column=0, row=2, padx=4, pady=2, sticky="ew")
self.forms[3].grid(column=1, row=0, padx=4, pady=2, sticky="ew")
self.forms[4].grid(column=1, row=1, padx=4, pady=2, sticky="ew")
self.forms[5].grid(column=1, row=2, padx=4, pady=2, sticky="ew")
self.forms_frame.grid_columnconfigure(0, weight=1)
self.forms_frame.grid_columnconfigure(1, weight=1)
self.forms_frame.grid_columnconfigure(2, weight=0)
if __name__ == "__main__":
app = App()
app.mainloop()
You've probably already tried this, but can you call update() on your root widget?
You might also need to pack() again, first.

Categories

Resources