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()
Related
in this code below i need to make a button if clicked use the entered number by user in entry widget (innenleiter) and if not, then use the variable formula and proceed.
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
import scipy.special as scs
import scipy.optimize as sco
import matplotlib.pyplot as plt
import numpy as np
def button_clear():
eps_r_Entry.delete(0, END)
impedanz_Entry.delete(0, END)
aussenleiter_Entry.delete(0, END)
innenleiter_Entry.delete(0, END)
def result_function():
c0 = 299792458
m0 = 4 * np.pi * 1e-7
e0 = 1 / (m0 * c0 ** 2)
z0 = np.sqrt(m0 / e0)
zl = float(impedanz_Var.get())
eps_r = float(eps_r_Var.get())
aus_d = float(aussenleiter_Var.get())
# in_d = float(innenleiter_Var.get())
''''
here i need a button if clicked use the number entered in Entry widget (innenleiter)
if not, take this variable and proceed (in_d = aus_d / (np.e ** (zl * 2 * np.pi *
np.sqrt(eps_r) / z0))
'''
in_d = aus_d / (np.e ** (zl * 2 * np.pi * np.sqrt(eps_r) / z0))
r1 = np.sqrt(eps_r) * aus_d / 2
r = np.sqrt(eps_r) * in_d / 2
a = r1 / r
z = z0 / (2 * np.pi * np.sqrt(eps_r)) * np.log(aus_d / in_d)
def wav_num(x):
return ((scs.jn(0, x*a) - scs.jn(2, x*a)) * (scs.yn(0, x) - scs.yn(2, x))
- (scs.yn(0, x*a) - scs.yn(2, x*a)) * (scs.jn(0, x) - scs.jn(2, x)))
x = np.arange(0.1, 1.0, 0.01)
test = wav_num(x)
etsi = sco.brentq(wav_num, 0.1, 1.0)
f_g = etsi * (a + 1) / (2 * np.pi * np.sqrt(m0 * e0) * (r1 + r) * 1e-3) / 1e9
result = round(f_g, 2)
result1 = round(z, 2)
result2 = round(in_d, 2)
Result_label.config(text='f_g : ' + str(result))
Result_label1.config(text='impedanz : ' + str(result1))
Result_label2.config(text='innenleiter D/O : ' + str(result2))
# fig = plt.figure(1)
plt.close()
plt.figure(1)
plt.plot(x, test)
plt.grid(True)
plt.savefig("result.png", dpi=70)
logo = Image.open('result.png')
logo = ImageTk.PhotoImage(logo)
logo_label = tk.Label(image=logo)
logo_label.image = logo
logo_label.grid(row=13, column=8, columnspan=4)
return logo
root = tk.Tk()
root.title("Coax TE Mode")
root.geometry("1400x1080")
root.config(background="#145")
var = DoubleVar()
# generate the window
title = Label(root, text="Coax TE Mode", font=('Helvetica', 22), bg="#145", fg="white")
title.grid(row=0, column=3, padx=20, pady=20)
leerZeile = Label(root, text="", bg="#145", fg="#145")
leerZeile.grid(row=1, column=1)
leerZeile = Label(root, text="", bg="#145", fg="#145")
leerZeile.grid(row=2, column=1)
# Impedanz = Zl (in die gleichung als Z gezeichnet)
impedanz_Label = Label(root, text="Impedanz", font=12, bg="#145", fg="white")
impedanz_Label.grid(row=6, column=0, padx=10, pady=10)
impedanz_Var = DoubleVar()
impedanz_Entry = Entry(root, textvariable=impedanz_Var, width=32, borderwidth=5, )
impedanz_Entry.grid(row=6, column=1, columnspan=4, padx=10, pady=10)
# Innenleiter = d (in die gleichung als d gezeigt)
innenleiter_Label = Label(root, text="Innenleiter", font=12, bg="#145", fg="white")
innenleiter_Label.grid(row=4, column=0, padx=10, pady=10)
innenleiter_Var = DoubleVar()
innenleiter_Entry = Entry(root, textvariable=innenleiter_Var, width=32, borderwidth=5)
innenleiter_Entry.grid(row=4, column=1, columnspan=4, padx=10, pady=10)
# Aussenleiter = D (in die gleichung als D gezeigt)
aussenleiter_Label = Label(root, text="Außenleiter", font=12, bg="#145", fg="white")
aussenleiter_Label.grid(row=5, column=0, padx=10, pady=10)
aussenleiter_Var = DoubleVar()
aussenleiter_Entry = Entry(root, textvariable=aussenleiter_Var, width=32, borderwidth=5)
aussenleiter_Entry.grid(row=5, column=1, columnspan=4, padx=10, pady=10)
# eps_r = in die gleichung als Permittivity dry air 1.000594
eps_r_Label = Label(root, text="eps_r", font=12, bg="#145", fg="white")
eps_r_Label.grid(row=7, column=0, padx=10, pady=10)
eps_r_Var = DoubleVar()
eps_r_Entry = Entry(root, textvariable=eps_r_Var, width=32, borderwidth=5)
eps_r_Entry.grid(row=7, column=1, columnspan=4, padx=10, pady=10)
# Result btn
Result_btn = Button(command=result_function, text="Result", bg="#145", fg="white", font=12)
Result_btn.grid(row=8, column=2, padx=10, pady=10)
# Show Result tkinter root window
Result_label = Label(root, text="", bg="#145", fg="white", font=14)
Result_label.grid(row=10, column=2, columnspan=20, padx=2, pady=2)
Result_label1 = Label(root, text="", bg="#145", fg="white", font=14)
Result_label1.grid(row=11, column=2, columnspan=20, padx=2, pady=2)
Result_label2 = Label(root, text="", bg="#145", fg="white", font=14)
Result_label2.grid(row=12, column=2, columnspan=20, padx=2, pady=2)
# clear btn soll entry fields räumen
plt_btn = Button(text="clear", command=button_clear, bg="#145", fg="white", font=12)
plt_btn.grid(row=8, column=3, padx=10, pady=10)
# Exit
exit_btn = Button(root, text="Exit", bg="#145", fg="white", font=12, command=root.quit)
exit_btn.grid(row=8, column=4, padx=10, pady=10)
root.mainloop()
So this seems like a simple issue but let me know if I misunderstood. What you want to do is disable and enable a text widget. To do this you would use some_text_widget.config(state="enabled") to enable the widget and/or some_text_widget.config(state="disabled"). Does this work for you?
I need to fill entry boxes with values selected from dictionary.
List of dictionaries is compiled from a csv file. Here is the code:
import os
import csv
from tkinter import *
import tkinter as tk
from tkinter.filedialog import *
def show():
record =[]
details = open('c.record.csv','r')
reader = csv.DictReader(details)
for line in reader:
record.append(line)
return record
def recordDetails():
name = ent_user.get()
password = ent_pw.get()
city = ent_city.get()
code = ent_code.get()
if len(name) != 0 and len(password) != 0 and len(city) != 0 and len(code) != 0:
with open('c.record.csv', 'a') as add:
w = csv.writer(add)
w.writerow([name,password,city,code])
add.close
lbl_result["text"] = "record saved"
else:
lbl_result["text"] = "values cannot be empty"
return True
def SaveToFile():
name = ent_user.get()
data = show()
for elem in data:
if name in elem.values():
lbl_result["text"] = "record exist already"
return False
recordDetails()
return True
def display() :
lbl_result["text"] = show()
record = show()
for n, dicts in enumerate(record):
for v, k in dicts.items():
position = n
user = dicts['name']
lbl_record = tk.Label(master=frm_details, height=1, width=40, bg = 'white', relief=tk.GROOVE, text=user,justify="right")
lbl_record.grid(row=1+position, column=0, padx=5)
def select():
Clear()
ent_user.insert(tk.END,dicts['name'])
ent_pw.insert(tk.END,dicts['password'])
ent_city.insert(tk.END,dicts['city'])
ent_code.insert(tk.END,dicts['code'])
btn_recSelect = tk.Button(master=frm_details ,width=5, bg = 'white', text='select',command=select)
btn_recSelect.grid(row=1+position, column=1, padx=2,sticky=tk.W)
return True
def Connect():
if len(ent_user.get()) != 0:
lbl_result["text"] = "connecting to "+ent_user.get()
def Clear() :
user = ent_user.delete(0,END)
pw = ent_pw.delete(0,END)
city = ent_city.delete(0,END)
code = ent_code.delete(0,END)
#def update(window):
#window.update()
screen = tk.Tk()
screen.title ("tk files interaction")
screen.minsize(width=400, height=300)
screen.maxsize(width=900, height=700)
screen.rowconfigure(0, minsize=50, weight=1)
screen.columnconfigure(0, minsize=60, weight=1)
screen.update()
#FORM to collect connectivity details
frm_connEntryArea = tk.Frame(master=screen,height=10, borderwidth=1, highlightbackground="orange", highlightthickness=1)
frm_connEntryArea.grid(column=0, row=0, sticky=tk.N, padx=10, pady=5)
lbl_user = tk.Label(master=frm_connEntryArea, text="name:")
lbl_user.grid(column=0, row=0, sticky=tk.NW, padx=5, pady=3)
ent_user = tk.Entry(master=frm_connEntryArea,width=30)
ent_user.grid(column=1, row=0, sticky=tk.NW, padx=5, pady=3)
lbl_pw = tk.Label(master=frm_connEntryArea, text="password:")
lbl_pw.grid(column=0, row=1, sticky=tk.NW, padx=5, pady=3)
ent_pw = tk.Entry(master=frm_connEntryArea,width=30)
ent_pw.grid(column=1, row=1, sticky=tk.NW, padx=5, pady=3)
lbl_city = tk.Label(master=frm_connEntryArea, text="city")
lbl_city.grid(column=0, row=2, sticky=tk.NW, padx=5, pady=3)
ent_city = tk.Entry(master=frm_connEntryArea,width=30)
ent_city.grid(column=1, row=2, sticky=tk.NW, padx=5, pady=3)
lbl_code = tk.Label(master=frm_connEntryArea, text="code:")
lbl_code.grid(column=0, row=3, sticky=tk.NW, padx=5, pady=3)
ent_code = tk.Entry(master=frm_connEntryArea,width=30)
ent_code.grid(column=1, row=3, sticky=tk.NW, padx=5, pady=3)
ent_code.insert(tk.END,"20")
ent_code.bind("<Button-1>", lambda event: clear_entry(ent_code))
#connect,save and clear details
btn_save = tk.Button(master=frm_connEntryArea,text="Save",width=10,fg="black",command=SaveToFile)
btn_save.grid(column=0, row=4, sticky=tk.NW, padx=5, pady=3)
btn_clear = tk.Button(master=frm_connEntryArea,text="Clear",width=10,fg="black",command=Clear)
btn_clear.grid(column=1, row=4, sticky=tk.NW, padx=5, pady=3)
btn_conn = tk.Button(master=frm_connEntryArea,text="Connect",width=10,fg="black",command=Connect)
btn_conn.grid(column=2, row=4, sticky=tk.NW, padx=5, pady=3)
#FORM to shows connectivity results and errors
frm_logs = tk.Frame(master=screen,height=10,bg="gray",relief=tk.GROOVE,highlightbackground="orange")
frm_logs.grid(column=0, row=1, sticky=tk.NW, padx=5, pady=3)
lbl_result = tk.Label(master=frm_logs, height=8, width=50,relief=tk.GROOVE, bg = 'white', text="Logs",wraplength=300,justify="left")
lbl_result.grid(row=0, column=0)
#FORM to shows Existing Record
frm_record = tk.Frame(master=screen,height=10,bg="gray")
frm_record.grid(column=1, row=1, sticky=tk.N, padx=5, pady=3)
lbl_record = tk.Label(master=frm_record, height=1, width=40, bg = 'white', relief=tk.GROOVE, text='Record',wraplength=200,justify="left")
lbl_record.grid(row=0, column=0, padx=5)
btn_recDisplay = tk.Button(master=frm_record ,width=5, bg = 'white', text='Display',command =display)
btn_recDisplay.grid(row=0, column=1, padx=2,sticky=tk.W)
frm_details = tk.Frame(master=frm_record,height=10,bg="gray")
frm_details.grid(row=1, column=0, sticky=tk.NW, padx=5, pady=3)
lbl_record = tk.Label(master=frm_details , height=1, width=30, bg = 'white', relief=tk.GROOVE, text='user',justify="right")
lbl_record.grid(row=0, column=0, padx=5)
#FORM to exit
frm_exit = tk.Frame(master=screen,height=50,width= 300, bg="orange")
frm_exit.grid(column=1, row=0, sticky=NE, padx=5, pady=3)
frm_exit.grid_propagate(0)
btn_refresh = tk.Button(master=frm_exit, text="Refresh")
btn_refresh.grid(row=2, column=3,sticky=E, padx=10,pady=10)
btn_exit = tk.Button(master=frm_exit, text="Exit", command=screen.destroy)
btn_exit.grid(row=2, column=4, sticky=E, padx=10,pady=10)
# added at the end
screen.mainloop()
csv structure:
name,password,city,code
apple,1234,rome,20
banana,2345,paris,20
cherry,3456,london,21
I am concerned with the def display() : and def select(): functions. These works in displaying and selecting. The problem is when ‘select’ is pressed the latest dictionary value form the list is used to fill the entries boxes, I would like the entries to be filled with the values that correspond to the user display in the line.
I have found the solution.
I have adjust the code with the guidance found here:
https://www.geeksforgeeks.org/looping-through-buttons-in-tkinter/
def select(u,pwd,cy,co):
Clear()
ent_user.insert(tk.END,u)
ent_pw.insert(tk.END,pwd)
ent_city.insert(tk.END,cy)
ent_code.insert(tk.END,co)
def display() :
lbl_result["text"] = show()
record = show()
for n, line in enumerate(record):
position = n
user = line['name']
for k,v in line.items():
def action(x = line['name'], p = line['password'], c = line['city'], d = line['code']):
return select(x,p,c,d)
lbl_record = tk.Label(master=frm_details, height=1, width=40, bg = 'white', relief=tk.GROOVE, text=user,justify="right")
lbl_record.grid(row=1+position, column=0, padx=5)
btn_recSelect = tk.Button(master=frm_details ,width=5, bg = 'white', text='select',command= action)
btn_recSelect.grid(row=1+position, column=1, padx=2,sticky=tk.W)
return True
I had to create an aditional function to point to action the entry update and add an addidional for looop, the first loop through the list, the second through the dictionary items.
I want to create a program that is a Bakery online shop but I'm stuck on a show bill page, I want to show the menu list, Amount, Price, Total of that cake or drink in one line and the last line is all total
this my code :
from tkinter import*
def mainwindow():
main = Tk()
x = main.winfo_screenwidth() / 2 - (w / 2)
y = main.winfo_screenheight() / 2 - (h / 2)
main.geometry("%dx%d+%d+%d" % (w, h, x, y))
main.title("Cake_Shop by Winit Auppkarasakun")
main.option_add("*font", "times 17 bold")
menubar = Menu(main)
filemenu = Menu(menubar, tearoff=False)
filemenu.add_command(label="Menu", command=menu)
filemenu.add_command(label="Checkout", command=checkout)
filemenu.add_command(label="Exit", command=main.quit)
menubar.add_cascade(label="File", menu=filemenu)
main.configure(bg="pink", menu=menubar)
return main
def menu():
frame1 = Frame(main, bg="yellow")
frame1.place(x=0, y=0, width=w, height=h)
frame1.columnconfigure((0,1), weight=1)
frame1.rowconfigure((0,1,2,3,4,5,6,7,8,9), weight=1)
Label(frame1, text="Strawberry Cake : ", bg="yellow", fg="blue", font="times 18 bold").grid(row=0, column=0)
Label(frame1, image = img_menu_1, bg="yellow").grid(row=1, column=0)
Label(frame1, text="Price 85", bg="yellow", fg="black").grid(row=2, column=0)
Spinbox(frame1, from_=0, to=10, textvariable=cake_spy1).grid(row=3, column=0)
Label(frame1, text="Cheese Cake : ", bg="yellow", fg="blue", font="times 18 bold").grid(row=4, column=0)
Label(frame1, image = img_menu_2, bg="yellow").grid(row=5, column=0)
Label(frame1, text="Price 95", bg="yellow", fg="black").grid(row=6, column=0)
Spinbox(frame1, from_=0, to=10, textvariable=cake_spy2).grid(row=7, column=0)
Label(frame1, text="Strawberry Mixed : ", bg="yellow", fg="blue", font="times 18 bold").grid(row=0, column=1)
Label(frame1, image = img_drink_1, bg="yellow").grid(row=1, column=1)
Label(frame1, text="Price 120", bg="yellow", fg="black").grid(row=2, column=1)
Spinbox(frame1, from_=0, to=10, textvariable=drink_spy1).grid(row=3, column=1)
Label(frame1, text="Orange Mixed : ", bg="yellow", fg="blue", font="times 18 bold").grid(row=4, column=1)
Label(frame1, image = img_drink_2, bg="yellow").grid(row=5, column=1)
Label(frame1, text="Price 140", bg="yellow", fg="black").grid(row=6, column=1)
Spinbox(frame1, from_=0, to=10, textvariable=drink_spy2).grid(row=7, column=1)
def checkout():
frame2 = Frame(main, bg="lightgreen")
frame2.place(x=0, y=0, width=w, height=h)
frame2.rowconfigure((0,1,2,3,4,5), weight=1)
frame2.columnconfigure((0,1,2,3), weight=1)
Label(frame2, text="Menu list", bg="lightgreen", fg="black").grid(row=0, column=0, sticky=N, pady=10)
Label(frame2, text="Amount", bg="lightgreen", fg="black").grid(row=0, column=1, sticky=N, pady=10)
Label(frame2, text="Price", bg="lightgreen", fg="black").grid(row=0, column=2, sticky=N, pady=10)
Label(frame2, text="Total(Baths)", bg="lightgreen", fg="black").grid(row=0, column=3, sticky=N, pady=10)
for i,des in enumerate(name_menu_list):
Label(frame2, text=des["Menu list"]).grid(row=i+1, column=0, sticky="news")
Label(frame2, text=des["Amount"]).grid(row=i+1, column=1, sticky="news")
Label(frame2, text=des["Price"]).grid(row=i+1, column=2, sticky="news")
Label(frame2, text=des["Total(Baths)"]).grid(row=i+1, column=3, sticky="news")
def calculate():
global total
global menu_total
menu_total = 0
total = 0
if cake_spy1.get() > 0:
menu_total = cake_spy1.get() * 85
total = total + menu_total
show_menu = {"Menu list":"Strawberry Cake", "Amount":cake_spy1, "Price":85, "Total(Baths)":menu_total}
elif cake_spy2.get() > 0:
menu_total = cake_spy2.get() * 95
total = total + menu_total
show_menu = {"Menu list":"Cheese Cake", "Amount":cake_spy2, "Price":95, "Total(Baths)":menu_total}
elif drink_spy1.get() > 0:
menu_total = drink_spy1.get() * 120
total = total + menu_total
show_menu = {"Menu list":"Strawberry Mixed", "Amount":drink_spy1, "Price":120, "Total(Baths)":menu_total}
elif drink_spy2.get() > 0:
menu_total = drink_spy2.get() * 140
total = total + menu_total
show_menu = {"Menu list":"Orange Mixed", "Amount":drink_spy2, "Price":140, "Total(Baths)":menu_total}
name_menu_list.append(show_menu)
menu_total = 0
total = 0
w = 800
h = 700
main = mainwindow()
cake_spy1 = StringVar()
cake_spy2 = StringVar()
drink_spy1 = StringVar()
drink_spy2 = StringVar()
frame0 = Frame(main, bg="pink") #for homepage
frame0.grid(row=0, column=0, sticky="news")
img_home = PhotoImage(file="images/myshop.png")
Label(frame0, image=img_home, bg="pink").grid(row=0, column=0, sticky="news", padx=130, pady=40)
Label(frame0, text="...Welcome to my resturent...", bg="pink", fg="black", font="times 25 bold").grid(row=1, column=0)
img_menu_1 = PhotoImage(file="images/cake1.png")
img_menu_2 = PhotoImage(file="images/cake2.png")
img_drink_1 = PhotoImage(file="images/drink1.png")
img_drink_2 = PhotoImage(file="images/drink2.png")
name_menu_list = []
menu_name = StringVar()
main.mainloop()
this all my code the problem function is checkout and calculate
Thank you for helping me
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()
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.