I've tried to search this topic up, but it has been very confusing, as I don't use/quite understand stdout/stderr... However, I have this code right now that prints a list onto the console. Can someone explain to me how I could get this to print directly onto a GUI Textbox? My code:
from tkinter import *
import math
class TimeGenerator:
def __init__(self,master):
frame = Frame(master)
frame.grid()
label_iso = Label(root, text="Isotope A, Element")
label_vol = Label(root, text="Voltage")
label_range = Label(root, text="Charge Range")
entry_iso = Entry(root)
entry_vol = Entry(root)
entry_range = Entry(root)
label_iso.grid(row=0, sticky=E)
label_vol.grid(row=1, sticky=E)
label_range.grid(row=2, sticky=E)
entry_iso.grid(row=0, column=1)
entry_vol.grid(row=1, column=1)
entry_range.grid(row=2,column=1)
button = Button(root, text='Time Range', command=self.calculateTime)
button.grid(row=3, columnspan=2)
self.iso = entry_iso
self.vol = entry_vol
self.r = entry_range
def calculateTime(self):
x = 5
self.iso = self.iso.get().replace(" ", "")
list = []
for e in self.iso.split(","):
list.append(e)
f = open("/Users/LazyLinh/PycharmProjects/mass.mas12.txt", "r")
i = 0
while (i < 40):
header = f.readline()
i += 1
self.mass = 0
for line in f:
line = line.strip()
columns = line.split()
if (list[0] == columns[3]):
if (list[1] == columns[4]):
if (len(columns) == 16):
self.mass = float(columns[13].replace("#","")) + float(columns[14].replace("#",""))
else:
self.mass = float(columns[12].replace("#","")) + float(columns[13].replace("#",""))
self.r = self.r.get().replace(" ", "")
tup = tuple(int(x) for x in self.r.split(","))
list = []
for q in range(tup[0], tup[1] + 1):
y = x * math.sqrt(self.mass / (2 * q * float(self.vol.get())))
list.append(y)
i = tup[0]
for time in list:
print(i, ':', time)
i = i + 1
root = Tk()
b = TimeGenerator(root)
root.mainloop()
Thank you!
Somewhere in your code you need to create a text widget:
class TimeGenerator:
def __init__(self,master):
...
self.text = Text(...)
...
Later, use the insert method of the text widget instead of a print statement:
for time in list:
self.text.insert("end", "%d: %s\n" % (i, time))
i = i + 1
Related
I did a tkinter window where an user has to select some items in a listbox which displays two radiobuttons. If the user selects one radiobutton and then deselects the item in the listbox, radiobuttons are deleted. The problem is that if user selects the same item as previously, the radiobutton is already selected. I would like they are empty when they are created again.
Thanks in advance
from tkinter import *
import tkinter as tk
class Application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.dictLabel = dict()
self.createWidgets()
def createWidgets(self):
self.ListNumber = ['one', 'two', 'three', 'four']
self.labelListNumber = tk.Label(self, text=' Select a Number : ')
self.labelListNumber.place(x=40, y=30)
self.frame = Frame(self)
self.frame.place(x=200, y=30)
self.list = Listbox(self.frame, exportselection=False,activestyle = tk.NONE, height=5, selectmode="multiple")
self.list.pack(side='left', fill='y')
for each_item in range(len(self.ListNumber)):
self.list.insert(END, self.ListNumber[each_item])
self.scrollbar = Scrollbar(self.frame, orient="vertical", command=self.list.yview)
self.scrollbar.pack(side='right', fill='y')
self.list.config(yscrollcommand=self.scrollbar.set)
self.dictRadioButtonValue = dict()
self.list.bind('<<ListboxSelect>>',self.createRadioButton)
def createRadioButton(self, evt):
index = self.list.curselection() # grab the index
c = 1
if len(index) == 0 or len(self.dictLabel) != 0:
for e in self.dictLabel:
self.dictLabel[e][0].place_forget()
self.dictLabel[e][1].place_forget()
self.dictLabel[e][2].place_forget()
del self.dictLabel
self.dictLabel = dict()
for i in index:
item = self.list.get(i)
if not item in self.dictRadioButtonValue:
if len(self.dictRadioButtonValue) > len(index):
if not item in self.dictLabel[item]:
del self.dictRadioButtonValue[item]
else :
radioButtonValue = tk.IntVar()
radioButtonValue.set(' ')
self.dictRadioButtonValue[item] = radioButtonValue
L = tk.Label(self, text=f"Number selected is {item}")
radiobtn5 = tk.Radiobutton(self, text="Yes", variable = self.dictRadioButtonValue[item], value = 5)
radiobtn7 = tk.Radiobutton(self, text="No", variable = self.dictRadioButtonValue[item], value = 6)
L.place(x=350, y=10+(c * 20))
radiobtn5.place(x=500, y=10 + (c * 20))
radiobtn7.place(x=550, y=10 + (c * 20))
self.dictLabel[item] = L, radiobtn5, radiobtn7
c = c+1
if __name__ == "__main__":
app = Application()
app.geometry("700x250")
app.mainloop()
It is because the deselected item is not removed from self.dictRadioButtonValue.
Create a copy of self.dictRadioButtonValue and then remove the items that are used from the copy. At the end, remove remaining items in copy from self.dictRadioButtonValue:
def createRadioButton(self, evt):
index = self.list.curselection() # grab the index
c = 1
if len(index) == 0 or len(self.dictLabel) != 0:
for e in self.dictLabel:
self.dictLabel[e][0].place_forget()
self.dictLabel[e][1].place_forget()
self.dictLabel[e][2].place_forget()
del self.dictLabel
self.dictLabel = dict()
copy = self.dictRadioButtonValue.copy()
for i in index:
item = self.list.get(i)
if not item in self.dictRadioButtonValue:
# new item selected
radioButtonValue = tk.IntVar(value=' ')
self.dictRadioButtonValue[item] = radioButtonValue
else:
# remove current item from copy
del copy[item]
L = tk.Label(self, text=f"Number selected is {item}")
radiobtn5 = tk.Radiobutton(self, text="Yes", variable = self.dictRadioButtonValue[item], value = 5)
radiobtn7 = tk.Radiobutton(self, text="No", variable = self.dictRadioButtonValue[item], value = 6)
L.place(x=350, y=10+(c * 20))
radiobtn5.place(x=500, y=10 + (c * 20))
radiobtn7.place(x=550, y=10 + (c * 20))
self.dictLabel[item] = L, radiobtn5, radiobtn7
c = c+1
# remove remaining items in copy from self.dictRadioButtonValue
for item in copy:
del self.dictRadioButtonValue[item]
I'm trying to make an app in python/tkinter that allows you to create a roster for a hockey team. I want to generate the "new_roster" frame based on the parameter number of players on the team, and have thus managed to create a variable amount of entry boxes for each player, but am not able to extract the values from said entry boxes.
In my current code, a list is generated based on the number of players the user wants on their team by adding a "z" to an empty string. The next function then iterates through the list, sets the string = Entry(frame, xxx), I initially tried with an int, but it doesn't seem to matter. I also tried making the str a StringVar but it didn't work either.
Every time I try to reference the entry boxes after their creation like
a = (player_list[0])
b = a.get
I get the following error:
error: 'str' object has no attribute 'get'
it's kinda long so: https://repl.it/#masoneischens/StableToughTheories
The important parts:
My very convoluted list creation loop (entry2 = number of players on team)
for i in range(int(entry2.get())):
a = "z"
for u in range(i):
a += "z"
player_list.insert(i - 1, a)
The loop that actually creates the entry boxes (pr = appropriate row)
for n in player_list:
pr += 1
a= Entry(edit_roster, width = 15)
a.grid(row = pr, column =3)
The function that saves values to a csv file (fn = filename, s = name w/o ".csv")
def save_new_file(s):
global player_list
fn = str(s) + ".csv"
with open(fn, mode='w') as roster_file:
roster_writer = csv.writer(roster_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for i in player_list:
b = i.get()
roster_writer.writerow([b, "player 1 "])
Basically I need to be able to create and reference variables using a string as it's name, or some way to convert a string into proper variable name so I can extract values from entry boxes created using said strings.
The Error is occurring because you are calling get() method on strings.
Instead of calling get() method on player_list, do the following:
create a entry_list
global entry_list
entry_list = []
insert entries to entry list
entry_list.append(a)
call get() method on entries from entry_list
global entry_list
for i in entry_list:
print(i.get())
This is updated version of your code. Here I just printed the values from entries:
from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
import csv
import random
sample = Tk()
sample.geometry("500x500")
# lists
# functions
def switch_newroster():
new_roster.tkraise()
def switch_startpage():
start_page.tkraise()
def switch_loadroster():
load_roster.tkraise()
def get_file():
if entry_getfile_act.get() == "":
messagebox.showerror("ERROR!!", "Please enter a file name")
else:
print("good job")
def create():
global player_list
# ADD_1 Create new global entry_list #####
global entry_list
entry_list = []
player_list = []
number_list = []
pos_list = []
pr = 3
nr = 3
gr = 3
posr = 3
ar = 3
gaar = 3
if entry2.get() == "":
messagebox.showerror("ERROR!!", "Enter number of players")
return False
elif entry1.get() == "":
messagebox.showerror("ERROR!!", "Please enter a team name")
return False
elif int(entry2.get()) > 35 or int(entry2.get()) <= 0:
messagebox.showerror("ERROR!!", "Roster can contain 1-35 players")
else:
o = "we coolin my dude"
for i in range(int(entry2.get())):
a = "z"
for u in range(i):
a += "z"
player_list.insert(i - 1, a)
for i in range(int(entry2.get())):
a = i + 1
number_list.insert(i - 1, a)
for i in range(int(entry2.get())):
a = i + 1
pos_list.insert(i - 1, a)
print(player_list)
team_name = Label(edit_roster, text=entry1.get())
team_name.grid(row=1, column=3)
for n in player_list:
pr += 1
n = StringVar()
a = Entry(edit_roster, width=15, textvariable=n)
a.grid(row=pr, column=3)
# ADD_2 Append entries to entry_list #####
entry_list.append(a)
for n in number_list:
nr += 1
n = Entry(edit_roster, width=2)
n.grid(row=nr, column=1)
for n in pos_list:
posr += 1
pos = StringVar(sample)
pos.set(n + 1)
n = OptionMenu(edit_roster, pos, "G", "LW", "RW", "D")
n.grid(row=posr, column=5)
edit_roster.tkraise()
def editstats():
goal_list = []
assist_list = []
gaa_list = []
player_list = []
number_list = []
pos_list = []
pr = 3
nr = 3
gr = 3
posr = 3
ar = 3
gaar = 3
lbl5 = Label(edit_stats, text="G")
lbl5.grid(row=3, column=6)
lbl6 = Label(edit_stats, text="A")
lbl6.grid(row=3, column=5)
lbl7 = Label(edit_stats, text="GAA")
lbl7.grid(row=3, column=5)
for i in range(int(entry2.get())):
a = i + 1
goal_list.insert(i - 1, a)
for i in range(int(entry2.get())):
a = i + 1
gaa_list.insert(i - 1, a)
for i in range(int(entry2.get())):
a = "z"
for u in range(i + 1):
a += "z"
assist_list.insert(i - 1, a)
for n in goal_list:
gr += 1
n = Entry(edit_roster, width=2)
n.grid(row=gr, column=4)
for n in assist_list:
ar += 1
n = Entry(edit_roster, width=2)
n.grid(row=ar, column=2)
for n in gaa_list:
gaar += 1
n = Entry(edit_roster, width=2)
n.grid(row=gaar, column=1)
edit_roster.tkraise()
def save_new_file(s):
global player_list
# ADD_3 Get values from entries of entry_list #####
global entry_list
for i in entry_list:
print(i.get())
# fn = str(s) + ".csv"
# with open(fn, mode='w') as roster_file:
# roster_writer = csv.writer(roster_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
# roster_writer.writerow(['John Smith', 'Accounting', 'November'])
# roster_writer.writerow(['Erica Meyers', 'IT', 'March'])
# for i in player_list:
# b = i.get()
# roster_writer.writerow([b, "player 1 "])
def get_filename():
global player_list
print()
filename = simpledialog.askstring("input string", "What do you want to call your file?")
print(filename)
save_new_file(filename)
# frames
# start page
start_page = Frame(sample, bg="pink", height="50", width="60")
start_page.grid(row=0, column=0, sticky="nsew")
# new roster
new_roster = Frame(sample, bg="yellow")
new_roster.grid(row=0, column=0, sticky="nsew")
# editable roster
edit_roster = Frame(sample, bg="Blue")
edit_roster.grid(row=0, column=0, sticky="nsew")
# load roster
load_roster = Frame(sample)
load_roster.grid(row=0, column=0, sticky="nsew")
# edit stats
edit_stats = Frame(sample)
edit_stats.grid(row=0, column=0, sticky="nsew")
start_page.tkraise()
# buttons
# start page
new_roster_b = Button(start_page, command=switch_newroster, text="NEW ROSTER", height="2", width="10")
new_roster_b.grid(row=1, column=2)
load_roster_b = Button(start_page, command=switch_loadroster, text="LOAD ROSTER", height="2", width="10")
load_roster_b.grid(row=2, column=2)
# load roster
entry_getfile_b = Button(load_roster, text="Find", command=get_file)
entry_getfile_b.grid(row=2, column=3)
back_b = Button(load_roster, command=switch_startpage, text="Back")
back_b.grid(row=3, column=1)
# new roster
back_b = Button(new_roster, command=switch_startpage, text="Back")
back_b.grid(row=3, column=1)
create_b = Button(new_roster, command=create, text="Create Team")
create_b.grid(row=2, column=5)
# edit roster
save_b = Button(edit_roster, command=get_filename, text="Save")
save_b.grid(row=3, column=6)
# other widgets
# start page
# load roster
entry_lbl_getfile = Label(load_roster, text="Enter File NAME!!!")
entry_lbl_getfile.grid(row=2, column=1)
entry_getfile_act = Entry(load_roster)
entry_getfile_act.grid(row=2, column=2)
# new roster
lbl1 = Label(new_roster, text="Team Name:")
lbl1.grid(row=2, column=1)
lbl8 = Label(new_roster, text="Number of Players:")
lbl8.grid(row=2, column=3)
entry1 = Entry(new_roster)
entry1.grid(row=2, column=2)
entry2 = Entry(new_roster)
entry2.grid(row=2, column=4)
# edit roster
lbl2 = Label(edit_roster, text="#")
lbl2.grid(row=3, column=1)
lbl3 = Label(edit_roster, text="Name")
lbl3.grid(row=3, column=3)
lbl4 = Label(edit_roster, text="Pos.")
lbl4.grid(row=3, column=5)
sample.mainloop()
I'm just beginning to program in python and I'm using it to make a little program with an GUI (using tkinter) that can take data from an excel file (using openpyxl). Let the user change things when necesarry and then use a button to write the data from the entries to a data file (.dat) (preferable by updating the values in the defaultdict arrays and then write the .dat file) and use a modelling language (pyomo) to create a model with the provided data and solve it with the cbc solver.
I'm now sofar that I made the model, the graphical interface (which is filled with data from the excel file). However I can't get the data in the entries fields back (to write update the defaultdicts arrays). I understand the simple examples on stackoverflow (with entry.get()), but it didn't worked on my example (probably because I use notbook tabs, panels and frames or I messed something up).
I use notebook tabs instead of one page, because I will have more (around 5) other categories of data in the complete program. At last I want to make the programm is such a way that it can adapt to the input (so it does not know if there are going to be 3, 8 or 10 facilities). I use python version 3.5.1. Here is the link to the excel file: https://drive.google.com/file/d/0B5vmtJnltudJWW4xakZlYnQ3RTg/view?usp=sharing
import sys
from tkinter import ttk
import tkinter as tk
import openpyxl
import numpy as np
import os
from collections import defaultdict
from facility_panel import *
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.getdata()
self.tabes()
button_box = tk.Frame(self)
tk.Button(button_box, text='Create Planning', command=self.on_ok_clicked).grid(pady=15)
button_box.pack()
self.create_menu()
self.set_keybindings()
#staticmethod
def center_on_screen(toplevel):
toplevel.update_idletasks()
w = toplevel.winfo_screenwidth()
h = toplevel.winfo_screenheight()
size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
x = w/2 - size[0]/2
y = h/2 - size[1]/2
toplevel.geometry('%dx%d+%d+%d' % (size + (x, y)))
def set_keybindings(self):
self.bind_all('<Control-o>', lambda event: self.open_file())
self.bind_all('<Control-s>', lambda event: self.save_file())
self.bind_all('<Control-q>', self.quit_app)
self.bind_all('<Control-h>', lambda event: self.show_help())
self.bind_all('<Return>', lambda event: self.on_ok_clicked())
def on_ok_clicked(self):
print ('Entry text: %s' % self.entry.get())
print ('Scale value: %.1f' % self.scale.get())
print ('Checkbutton value: %i' % self.checkbox_val.get())
print ('Spinbox value: %i' % int(self.spinbox.get()))
print ('OptionMenu value: %s' % self.enum_val.get())
def create_menu(self):
menubar = tk.Menu(self)
fileMenu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label="File", underline=0, menu=fileMenu)
fileMenu.add_command(label="Open", underline=1, command=self.open_file, accelerator="Ctrl+O")
fileMenu.add_command(label="Save", underline=1, command=self.save_file, accelerator="Ctrl+S")
fileMenu.add_command(label="Quit", underline=1, command=self.quit_app, accelerator="Ctrl+Q")
helpMenu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label="Help", underline=0, menu=helpMenu)
helpMenu.add_command(label="Help", underline=1, command=self.show_help, accelerator="Ctrl+H")
helpMenu.add_command(label="About", underline=1, command=self.about_app)
self.config(menu=menubar)
def open_file(self):
"""Options are explained here: http://tkinter.unpythonic.net/wiki/tkFileDialog"""
filename = askopenfilename(title='Open a file')
if filename:
print ('Open and do something with %s' % filename)
def save_file(self):
"""Options are explained here: http://tkinter.unpythonic.net/wiki/tkFileDialog"""
filename = asksaveasfilename()
if filename:
print ('Save something to %s' % filename)
def quit_app(self):
app.destroy()
def show_help(self):
# FIXME: pressing return correctly closes dialog, but also incorrectly fires the main window's 'on_click' method
about_text = """
Contact: \n
example#hotmail.com"""
about_dialog = tk.Toplevel(self)
about_dialog.title('About App')
about_dialog.bind('<Escape>', lambda event: about_dialog.destroy())
about_dialog.bind('<Return>', lambda event: about_dialog.destroy())
App.center_on_screen(about_dialog)
tk.Message(about_dialog, text=about_text).pack()
button = tk.Button(about_dialog, text='Close', command=about_dialog.destroy).pack()
def about_app(self):
# FIXME: pressing return correctly closes dialog, but also incorrectly fires the main window's 'on_click' method
about_text = """
This application is made by Jan Jansen\n
version 0.7"""
about_dialog = tk.Toplevel(self)
about_dialog.title('About App')
about_dialog.bind('<Escape>', lambda event: about_dialog.destroy())
about_dialog.bind('<Return>', lambda event: about_dialog.destroy())
App.center_on_screen(about_dialog)
tk.Message(about_dialog, text=about_text).pack()
button = tk.Button(about_dialog, text='Close', command=about_dialog.destroy).pack()
def tabes(self):
nb = ttk.Notebook()
nb.pack(expand=1, fill="both")
# Frame to hold contentx
frame = tk.Frame(nb)
vscroll = tk.Scrollbar(frame, orient="vertical")
#panel['yscroll'] = vscroll.set
vscroll.pack(side="right", fill="y")
for facilityname in Facilities:
panel = FacilityPanel(frame, facilityname, capfacility[facilityname], safetystock[facilityname], maxpressure[facilityname], str(compulsorystarttime[facilityname]), str(compulsoryendtime[facilityname]), demandmatrix[facilityname][1], demandmatrix[facilityname][2], demandmatrix[facilityname][3], demandmatrix[facilityname][4], demandmatrix[facilityname][5], demandmatrix[facilityname][6], demandmatrix[facilityname][7])
panel.pack(fill="both")
# add to notebook (underline = index for short-cut character)
nb.add(frame, text='Facilities', underline=0, padding=2)
#--------------------------------------------------------------------------------------------------------
def getdata(self):
wb = openpyxl.load_workbook("data.xlsx")
ws = wb["Facilities"]
global Facilities
Facilities = ([])
row_count = ws.max_row
column_count = ws.max_column
global initlevel
initlevel = defaultdict(dict)
global capfacility
capfacility = defaultdict(dict)
global safetystock
safetystock = defaultdict(dict)
global maxpressure
maxpressure = defaultdict(dict)
global pressureincrease
pressureincrease = defaultdict(dict)
global compulsorystarttime
compulsorystarttime = defaultdict(dict)
global compulsoryendtime
compulsoryendtime = defaultdict(dict)
global demandmatrix
demandmatrix = defaultdict(dict)
for i in range(3, row_count+1, 1):
Facilities.append(ws.cell(row = i, column = 1).value)
initlevel[ws.cell(row = i, column = 1).value] = ws.cell(row = i, column = 2).value
capfacility[ws.cell(row = i, column = 1).value] = ws.cell(row = i, column = 3).value
safetystock[ws.cell(row = i, column = 1).value] = ws.cell(row = i, column = 4).value
maxpressure[ws.cell(row = i, column = 1).value] = ws.cell(row = i, column = 5).value
pressureincrease[ws.cell(row = i, column = 1).value] = ws.cell(row = i, column = 6).value
compulsorystarttime[ws.cell(row = i, column = 1).value] = ws.cell(row = i, column = 7).value
compulsoryendtime[ws.cell(row = i, column = 1).value] = ws.cell(row = i, column = 8).value
for j in range (9, column_count+1, 1):
demandmatrix[ws.cell(row = i, column = 1).value][ws.cell(row = 2, column = j).value] = ws.cell(row = i, column = j).value
if __name__ == "__main__":
app = App()
app.title("Planning")
toplevel = app.winfo_toplevel()
toplevel.wm_state('zoomed')
app.mainloop()
And this is the class I made:
from tkinter import *
class FacilityPanel(Frame):
def __init__(self, app, facility_name, capacity, safetystock, maxpressure, compulsorystarttime, compulsoryendtime, demandma, demanddi, demandwo, demanddo, demandvr, demandza, demandzo):
Frame.__init__(self, app)
group = LabelFrame(self, text=facility_name)
group.pack(side =LEFT)
group.enable_facility = IntVar()
enable_button = Checkbutton(group, variable = group.enable_facility,
command = print("toggle"))
enable_button.pack(side = LEFT)
enable_button.select()
group.init_level = IntVar()
init_label = Label(group, text="Current Level: 5,06 m\u00B3")
init_label.pack(side = LEFT)
group.capacity = DoubleVar()
capacity_label = Label(group, text="Capacity:")
capacity_label.pack(side = LEFT)
capacity_entry = Entry(group, width=8)
capacity_entry.pack(side = LEFT)
capacity_entry.insert(0, capacity)
capacity_label_unit = Label(group, text="kg ")
capacity_label_unit.pack(side = LEFT)
group.safetystock = DoubleVar()
safetystock_label = Label(group, text="Safetystock:")
safetystock_label.pack(side = LEFT)
safetystock_entry = Entry(group, width=8)
safetystock_entry.pack(side = LEFT)
safetystock_entry.insert(0, safetystock)
safetystock_label_unit = Label(group, text="kg ")
safetystock_label_unit.pack(side = LEFT)
group.maxpressure = DoubleVar()
maxpressure_label = Label(group, text="Maxpressure:")
maxpressure_label.pack(side = LEFT)
maxpressure_entry = Entry(group, width=8)
maxpressure_entry.pack(side = LEFT)
maxpressure_entry.insert(0, maxpressure)
maxpressure_label_unit = Label(group, text="bar ")
maxpressure_label_unit.pack(side = LEFT)
group.comp_start_time = DoubleVar()
comp_time1_label = Label(group, text="Unload time window:")
comp_time1_label.pack(side = LEFT)
comp_start_time_entry = Entry(group, width=8)
comp_start_time_entry.pack(side = LEFT)
comp_start_time_entry.insert(0, compulsorystarttime)
comp_time2_label = Label(group, text="-")
comp_time2_label.pack(side = LEFT)
comp_end_time_entry = Entry(group, width=8)
comp_end_time_entry.pack(side = LEFT)
comp_end_time_entry.insert(0, compulsoryendtime)
comp_time3_label = Label(group, text="hours ")
comp_time3_label.pack(side = LEFT)
group.demandmaandag = DoubleVar()
demandmaandag_label = Label(group, text="Maandag:")
demandmaandag_label.pack(side = LEFT)
demandmaandag_entry = Entry(group, width=8)
demandmaandag_entry.pack(side = LEFT)
demandmaandag_entry.insert(0, demandma)
demandmaandag_label_unit = Label(group, text="kg ")
demandmaandag_label_unit.pack(side = LEFT)
group.demanddinsdag = DoubleVar()
demanddinsdag_label = Label(group, text="Dinsdag:")
demanddinsdag_label.pack(side = LEFT)
demanddinsdag_entry = Entry(group, width=8)
demanddinsdag_entry.pack(side = LEFT)
demanddinsdag_entry.insert(0, demanddi)
demanddinsdag_label_unit = Label(group, text="kg ")
demanddinsdag_label_unit.pack(side = LEFT)
group.demandwoensdag = DoubleVar()
demandwoensdag_label = Label(group, text="Woensdag:")
demandwoensdag_label.pack(side = LEFT)
demandwoensdag_entry = Entry(group, width=8)
demandwoensdag_entry.pack(side = LEFT)
demandwoensdag_entry.insert(0, demandwo)
demandwoensdag_label_unit = Label(group, text="kg ")
demandwoensdag_label_unit.pack(side = LEFT)
group.demanddonderdag = DoubleVar()
demanddonderdag_label = Label(group, text="Donderdag:")
demanddonderdag_label.pack(side = LEFT)
demanddonderdag_entry = Entry(group, width=8)
demanddonderdag_entry.pack(side = LEFT)
demanddonderdag_entry.insert(0, demanddo)
demanddonderdag_label_unit = Label(group, text="kg ")
demanddonderdag_label_unit.pack(side = LEFT)
group.demandvrijdag = DoubleVar()
demandvrijdag_label = Label(group, text="Vrijdag:")
demandvrijdag_label.pack(side = LEFT)
demandvrijdag_entry = Entry(group, width=8)
demandvrijdag_entry.pack(side = LEFT)
demandvrijdag_entry.insert(0, demandvr)
demandvrijdag_label_unit = Label(group, text="kg ")
demandvrijdag_label_unit.pack(side = LEFT)
group.demandzaterdag = DoubleVar()
demandzaterdag_label = Label(group, text="Zaterdag:")
demandzaterdag_label.pack(side = LEFT)
demandzaterdag_entry = Entry(group, width=8)
demandzaterdag_entry.pack(side = LEFT)
demandzaterdag_entry.insert(0, demandza)
demandzaterdag_label_unit = Label(group, text="kg ")
demandzaterdag_label_unit.pack(side = LEFT)
group.demandzaterdag = DoubleVar()
demandzondag_label = Label(group, text="Zondag:")
demandzondag_label.pack(side = LEFT)
demandzondag_entry = Entry(group, width=8)
demandzondag_entry.pack(side = LEFT)
demandzondag_entry.insert(0, demandzo)
demandzondag_label_unit = Label(group, text="kg ")
demandzondag_label_unit.pack(side = LEFT)
I found something that worked on this question:
tkinter create labels and entrys dynamically
I made a global entry for every entryfield
this is my program so far.
from tkinter import *
import math
class TimeGenerator:
def __init__(self,master):
frame = Frame(master)
frame.grid()
label_iso = Label(root, text="Isotope A, Element")
label_vol = Label(root, text="Voltage")
label_range = Label(root, text="Charge Range")
entry_iso = Entry(root)
entry_vol = Entry(root)
entry_range = Entry(root)
label_iso.grid(row=0, sticky=E)
label_vol.grid(row=1, sticky=E)
label_range.grid(row=2, sticky=E)
entry_iso.grid(row=0, column=1)
entry_vol.grid(row=1, column=1)
entry_range.grid(row=2,column=1)
button = Button(root, text='Time Range')
button.grid(row=3, columnspan=2)
frame.bind(button,self.calculateTime())
self.iso = entry_iso.get()
self.vol = entry_vol.get()
self.r = entry_range.get()
def calculateTime(self):
x = 5
self.iso.replace(" ", "")
list = []
for e in self.iso.split(","):
list.append(e)
f = open("/Users/LazyLinh/PycharmProjects/mass.mas12.txt", "r")
i = 0
while (i < 40):
header = f.readline()
i += 1
for line in f:
line = line.strip()
columns = line.split()
if (list[0] == columns[5]):
if (list[1] == columns[6]):
self.mass = float(columns[13]) + float(columns[14])
self.r.replace(" ", "")
tup = tuple(int(x) for x in self.r.split(","))
list = []
for q in range(tup[0], tup[1] + 1):
y = x * math.sqrt(self.mass / (2 * q * float(self.vol)))
list.append(y)
i = tup[0]
for time in list:
print(i, ':', time)
i = i + 1
root = Tk()
b = TimeGenerator(root)
root.mainloop()
However, I got an error message saying iso attribute doesn't exist. Meanwhile, the shorter version of the code (just to test things out) below:
from tkinter import *
class TimeGenerator:
def __init__(self, master):
frame = Frame(master)
frame.grid()
label_iso = Label(root, text="Isotope A, Element")
label_vol = Label(root, text="Voltage")
label_range = Label(root, text="Charge Range")
entry_iso = Entry(root)
entry_vol = Entry(root)
entry_range = Entry(root)
label_iso.grid(row=0, sticky=E)
label_vol.grid(row=1, sticky=E)
label_range.grid(row=2, sticky=E)
entry_iso.grid(row=0, column=1)
entry_vol.grid(row=1, column=1)
entry_range.grid(row=2, column=1)
self.iso = entry_iso.get()
self.vol = entry_vol.get()
self.r = entry_range.get()
button = Button(root, text='Time Range')
button.grid(row=3, columnspan=2)
frame.bind(button, self.calculateTime())
def calculateTime(self):
self.iso.replace(" ", "")
list = []
for e in self.iso.split(","):
list.append(e)
f = open("/Users/LazyLinh/PycharmProjects/mass.mas12.txt", "r")
i = 0
while i < 40:
header = f.readline()
i += 1
for line in f:
line = line.strip()
columns = line.split()
if (list[0] == columns[5]):
if (list[1] == columns[6]):
self.mass = float(columns[13]) + float(columns[14])
self.r.replace(" ", "")
self.r.replace("(", "")
self.r.replace(")", "")
print(self.r)
root = Tk()
b = TimeGenerator(root)
root.mainloop()
There is no 'no attribute' errors, meaning self.r does create the attribute 'r'. But still, nothing gets printed in the console, and I can't see why. Can you please help me out?
P/S: I just started python a couple of days ago, so even if there's some very obvious mistakes, they might not be obvious to me, so please be kind :)
This line is wrong:
frame.bind(button,self.calculateTime())
Instead, try:
frame.bind(button,self.calculateTime)
In the first instance, you invoke calculateTime and pass the resulting value to bind. In the second instance, you pass a reference to the function itself to bind.
I want to make a grid of entry boxes that I can edit and save to a text file somewhere else, but every time I run my code, If I call the variable "e", I can only edit the last box that was made.
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.TXTlist = open('txtlist.txt', 'r+')
self.row = self.TXTlist.readline()
self.row = self.row.rstrip('\n')
self.row = self.row.replace('characters = ', "") #should end up being "6"
self.columns = self.TXTlist.readline()
self.columns = self.columns.rstrip('\n')
self.columns = self.columns.replace('columns = ', "") #should end up being "9"
i = 0
x = 0
for i in range (int(self.row)):
for x in range (int(self.columns)):
sroot = str('row' + str(i) + 'column' + str(x))
e = Entry(self, width=15)
e.grid(row = i, column = x, padx = 5, pady = 5, sticky = W)
e.delete(0, END)
e.insert(0, (sroot))
x = x + 1
x = 0
i = i + 1
root = Tk()
root.title("Longevity")
root.geometry("450x250")
app = Application(root)
root.mainloop()
I would store the entries in some sort of data structure to have easy access to them later. a list of lists would work nicely for this:
self.entries = []
for i in range (int(self.row)):
self.entries.append([])
for x in range (int(self.columns)):
...
e = Entry(self, width=15)
self.entries[-1].append(e)
...
Now you have a reference to the entry box:
self.entries[row_idx][col_idx]
And you can modify it however you want.