Run more loops at the same time? [closed] - python

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()

Related

tkinter entry fill with value selected from dictionary

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 can't get data from user to calculate

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

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()

Using StringVar data as a list

I've been following this website for a while. It is really helpful. So, thanks for all the useful tips.
I've been searching for this answer for the past two weeks without any success, so now I'm compelled to ask out of total frustration with my current obstacle.
How do you use StringVar as a list?
Basically, I was coding the following program for my wife. The code is pretty messy as it is my first program I've tried to code.
The idea was that I would take 3 variables; password, secret number and website and then do some work on them using if statements and lists to create a unique password.
First problem was that I couldn't restrict the character length of the entry widgets but in the end i solved that but i still want to limit the characters that can be input.
for instance in the website entry box, i want to allow only letters.
If I could convert StringVar to a list, I could do some work with messy if statements to allow only certain characters in each index but everythime i try it says that stringvars cant be used as a list.
I need them as a list to limit the type of characters that can be entered and also so that i can do work on the variables to get the final output.
CODE:
from Tkinter import *
import Tkinter
from PIL import Image, ImageTk
import os
Title= ("Helvetica", 20, "bold", "underline")
Heading= ("Courier", 20, "bold")
Body= ("Courier", 15)
Body1= ("Courier", 15, "bold")
notice= ("Courier", 10)
Body2= ("Courier", 15, "bold", "underline")
root = Tk()
root.title("Koala Series: Encrypter")
root.configure(background="#ffefd5")
root.geometry('{}x{}'.format(510, 600))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1) # not needed, this is the default behavior
root.rowconfigure(1, weight=1)
root.rowconfigure(2, weight=1)
website = StringVar()
Titlemsg = Label(root, text="Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
Titlemsg.grid( row=7, pady=25, sticky=N+S+E+W)
img1 = ImageTk.PhotoImage(Image.open("koala.jpeg"))
startpic = Label(root, image = img1, relief=RIDGE )
startpic.grid( row=10,pady=25, )
Head = Label(root,anchor=CENTER,text="Welcome to the Koala Encrypter \n\n A Koala series tool that allows you\n\n to Encrypt your passwords \n\n Click \'Start Encrypting\' to continue \n\n", font=Body, bg="#ffefd5", relief=RAISED,)
Head.grid( row=14, pady=25, columnspan=2, sticky=N+S+E+W)
web = Label(root, text="WEBSITE: ", font=Body, bg="#ffefd5", justify=CENTER,)
#website.set("Enter your website here")
entry = Entry(root,textvariable=website , justify=CENTER,relief=SUNKEN,cursor="pencil", takefocus=True )
Notice1 = Label( text="Please only insert the first 5 letters of the website!!",font=notice, bg="#ffefd5", fg="#0000ff",)
passw = Label(root, text="PASSWORD: ", font=Body, bg="#ffefd5", justify=CENTER)
passwordvar= StringVar()
entry1 = Entry(root, textvariable= passwordvar, justify=CENTER,relief=SUNKEN, cursor="pencil", takefocus=True )
Notice= Label(root, text="Your password must only be 5 characters long!!", font=notice, bg="#ffefd5", fg="#0000ff", justify=CENTER)
def callback(event):
if "<0>":
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Your secret number must be between 1 and 9:", font=Body1, fg="red", bg="#ffefd5")
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
secret = Label(root, text="SECRET NUMBER: ", font=Body, bg="#ffefd5" , justify=CENTER,)
numbervar = StringVar()
entry2 = Entry(root, textvariable=numbervar , justify=CENTER,relief=SUNKEN,cursor="pencil", takefocus=True)
entry2.bind("<0>", callback)
Notice2 = Label(root, text="your secret number must be between 1 and 9!!!", font=notice, bg="#ffefd5", fg="#0000ff", justify=CENTER)
img = ImageTk.PhotoImage(Image.open("Koalalogo.jpg"))
panel = Label(root, image = img, relief=SUNKEN)
correct= Label(root, text="Check the below details \n\n Click \'yes\' if they are correct \n\n Click \'No\' to go back \n\n", font=Body1, bg="#ffefd5")
yourwebsite = Label(root, text="The Website is :", font=Body, bg="#ffefd5")#
website1 = Label(root, font=Body2, bg="#ffefd5",fg= "#00009C", textvariable = website)#
yourpassword = Label(root, text="Your Password is:", font=Body, bg="#ffefd5")
yournumber1= Label(root, font=Body2, bg="#ffefd5",textvariable = numbervar , fg= "#00009C", )
yourpassword1 = Label(root, font=Body2, bg="#ffefd5",textvariable = passwordvar , fg= "#00009C", )
yournumber= Label(root, text="Your Secret Number is:", font=Body, bg="#ffefd5")
def restart():
Titlemsg.grid_forget()
correct.grid_forget()
yourwebsite.grid_forget()
website1.grid_forget()
yourpassword.grid_forget()
yourpassword1.grid_forget()
yournumber.grid_forget()
yournumber1.grid_forget()
panel.grid_forget()
toolbar.grid_forget()
yes.grid_forget()
no.grid_forget()
entry.delete(0,END)
entry1.delete(0,END)
entry2.delete(0,END)
Titlemsg.grid( row=7, pady=25, sticky=N+S+E+W)
startpic.grid( row=10,pady=25, )
Head.grid( row=14, pady=25, columnspan=2, sticky=N+S+E+W)
toolbar.grid( row=21, )
end.grid(column =3, row=1, sticky=N+S+E+W)
begin.grid(column =2, row=1, sticky=N+S+E+W)
def start():
#entry.destroy()
#entry1.destroy()
#entry2.destroy()
toolbar.grid_forget()
Titlemsg.grid_forget()
begin.grid_forget()
Head.grid_forget()
startpic.grid_forget()
web.grid(row=3, column=0, sticky= W+E)
entry.grid( row=3, column=1, padx=50)
passw.grid(row=10, column=0)
Notice1.grid(row=4, sticky=N+S+E+W, columnspan=2)
entry1.grid(row=10, column=1)
Notice.grid(row=11,column=0, columnspan=2,)
secret.grid(row=13, column=0)
entry2.grid( row=13, column=1)
Notice2.grid( row=14,column=0, columnspan=2,)
panel.grid(row=20,columnspan=2, pady=70)
confirm.grid(column =1, row=1)
reset.grid(column =2, row=1)
end.grid(column =3, row=1)
toolbar.grid(row=21, column=0, columnspan=2)
Titlemsg.grid(row=0, column=0, columnspan=2, sticky=E+W)
def Reset():
entry.delete(0,END)
entry1.delete(0,END)
entry2.delete(0,END)
def clear_text():
#entry.destroy()
#entry1.destroy()
#entry2.destroy()
panel.grid_forget()
entry.grid_forget()
entry1.grid_forget()
entry2.grid_forget()
web.grid_forget()
Notice.grid_forget()
passw.grid_forget()
secret.grid_forget()
Notice1.grid_forget()
Notice2.grid_forget()
confirm.grid_forget()
reset.grid_forget()
toolbar.grid_forget()
Titlemsg.grid_forget()
Titlemsg.grid(row=0, column=0, columnspan=2, sticky=E+W)
correct.grid(row=1, column=0, columnspan=2, sticky=E+W)
yourwebsite.grid(row=2,column=0,sticky=E+W, pady=5)
website1.grid(row=2, column=1, padx=65,sticky=E+W, pady=5)
yourpassword.grid(row=4, column=0,sticky=E+W, pady=5)
yourpassword1.grid(row=4, column=1, padx=65,sticky=E+W, pady=5)
yournumber.grid(row=6, column=0,sticky=E+W, pady=5)
yournumber1.grid(row=6, column=1, padx=65,sticky=E+W, pady=5)
panel.grid(row=8, column=0, columnspan=2, pady=50)
toolbar.grid(row=10, column=0, columnspan=2)
yes.grid(column =1, row=1)
no.grid(column =2, row=1)
def popup():
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Your password is:", font=Body1, fg="red", bg="#ffefd5")
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
pwd= Label(top, font=Body2, text="password", bg="#ffefd5", fg= "#00009C", ) #textvariable = newpassword ,
pwd.grid(row= 2, column=1,sticky=E+W,padx=15)
button = Button(top, text="OK", command=top.destroy, relief=RAISED )
button.grid(column =0,columnspan=2, row=4, sticky=N+S+E+W)
def helpmsg():
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Koala series 1.0 - Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
pwd= Label(top, font=Body, text="Free software to help you keep your acounts safe", bg="#ffefd5")
pwd.grid(row= 1,sticky=E+W,)
Titlems = Label(top, text="Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
Titlems.grid( row=0, pady=25, sticky=N+S+E+W)
button = Button(top, text="OK", command=top.destroy, relief=RAISED )
button.grid(column =0,columnspan=2, row=4, sticky=N+S+E+W)
max_len = 5
def on_write(*args):
s = website.get()
if len(s) > max_len:
website.set(s[:max_len])
website.trace_variable("w", on_write)
max_len1 = 5
def on_write(*args):
s = passwordvar.get()
if len(s) > max_len1:
passwordvar.set(s[:max_len1])
passwordvar.trace_variable("w", on_write)
max_len2 = 1
def on_write(*args):
s = numbervar.get()
if len(s) > max_len2:
numbervar.set(s[:max_len2])
numbervar.trace_variable("w", on_write)
toolbar = Frame(root)
reset = Button(toolbar, text="Reset", width=6, command=Reset, cursor="cross", relief=RAISED, takefocus=True )
end = Button(toolbar, text="Quit" ,command=root.destroy, relief=RAISED, cursor="X_cursor", takefocus=True)
end.grid(column =3, row=1, sticky=N+S+E+W)
begin = Button(toolbar, text="Start Encrypting", command=start, relief=RAISED, cursor="star",takefocus=True )
begin.grid(column =2, row=1, sticky=N+S+E+W)
confirm = Button(toolbar, text="Next", command =clear_text, cursor="star", relief=RAISED,takefocus=True )
yes = Button(toolbar, text="Yes", command =popup, cursor="star", relief=RAISED,takefocus=True )
no = Button(toolbar, text="No", command =restart, cursor="pirate", relief=RAISED, takefocus=True )
toolbar.grid( row=21, )
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Restart", command=restart)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.destroy)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu, )
helpmenu.add_command(label="About...", command=helpmsg)
app = root
root.mainloop()
# add functionality, fix validation
To restrict the type/number of characters that can be typed into an entry widget, you can use the entry validatecommand. Here is an example to allow only letters and another one to restrict the entry to 4 digits:
from tkinter import Tk, Entry, Label
def only_letters(action, char):
if action == "1":
# a character is inserted (deletion is 0) allow the insertion
# only if the inserted character char is a letter
return char.isalpha()
else:
# allow deletion
return True
def only_numbers_max_4(action, new_text):
if action == "1":
return new_text.isdigit() and len(new_text) <= 4
else:
return True
root = Tk()
# register validate commands
validate_letter = root.register(only_letters)
validate_nb = root.register(only_numbers_max_4)
Label(root, text="Only letters: ").grid(row=0, column=0)
e1 = Entry(root, validate="key", validatecommand=(validate_letter, '%d', '%S'))
# %d is the action code and %S the inserted/deleted character
e1.grid(row=0, column=1)
Label(root, text="Only numbers, at most 4: ").grid(row=1, column=0)
e2 = Entry(root, validate="key", validatecommand=(validate_nb, '%d', '%P'))
# %P is the new content of the entry after the modification
e2.grid(row=1, column=1)
root.mainloop()
For more details on entry validation, see http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html

Custom Tkinter Menu Placement

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()

Categories

Resources