I am working on python gui in tkinter and trying for a unit converter. Initially when I took my cursor at lower radio buttons they are automatically selected, please anyone help me how can I get rid of this.
from Tkinter import *
import tkMessageBox
root=Tk()
root.wm_title("Measurement Converter")
def Distance():
def sel():
print var.get()
L1 = Label(root, text="Enter Value :",font=20)
L1.grid(row=3,column=0,padx=(0,10),columnspan=2)
E1=Entry(root,justify=CENTER,width=20).grid(row=3,column=1,padx=(0,0),ipady=10,ipadx=20)
L2 = Label(root, text="units in-")
L2.grid(row=4,column=1,padx=(0,0))
var = IntVar()
R1 = Radiobutton(root, text="Meter", variable=var, value=1,command=sel)
R1.grid(row=4,column=1,padx=(120,0))
R2 = Radiobutton(root, text="Km", variable=var, value=2,command=sel)
R2.grid(row=4,column=1,padx=(240,0))
R3 = Radiobutton(root, text="Feet", variable=var, value=3,command=sel)
R3.grid(row=4,column=1,columnspan=2,padx=(100,0),pady=4)
L3 = Label(root, text="convert into-")
L3.grid(row=5,column=1,padx=(0,0))
var3 = IntVar()
RB1 = Radiobutton(root, text="Meter", variable=var3, value=1,command=sel)
RB1.grid(row=5,column=1,padx=(120,0))
RB2 = Radiobutton(root, text="Km", variable=var3, value=2,command=sel)
RB2.grid(row=5,column=1,padx=(240,0))
RB3 = Radiobutton(root, text="Feet", variable=var3, value=3,command=sel)
RB3.grid(row=5,column=1,columnspan=2,padx=(100,0),pady=5)
label1=Label(root, text='Select any Button to convert it in other Unit',bg="green",fg="white",justify=CENTER,borderwidth=1,font=20,padx=20 )
label1.grid(pady=15,padx=(15,15),row=0,column=1)
buttontext1=StringVar()
button1=Button(root,textvariable=buttontext1,font=25,padx=5,pady=5,width=15,command=Distance,bg='#FF0000')
buttontext1.set("Distance")
button1.grid(row=1,column=0,padx=(100,00))
buttontext2=StringVar()
button2=Button(root,textvariable=buttontext2,font=25,padx=5,pady=5,width=15,command=Distance,bg='#66FF66')
buttontext2.set("Weight")
button2.grid(row=1,column=2,padx=(0,100))
buttontext3=StringVar()
button3=Button(root,textvariable=buttontext3,font=25,padx=5,pady=5,width=15,command=Distance,bg='#3399CC')
buttontext3.set("Temprature")
button3.grid(row=2,column=0,pady=50,padx=(100,0))
buttontext4=StringVar()
button4=Button(root,textvariable=buttontext4,font=25,padx=5,pady=5,width=15,command=Distance,bg='#CCFF00')
buttontext4.set("Volume")
button4.grid(row=2,column=2,padx=(0,100))
root.mainloop()
I had few time so I developed this quickly. It's just a starting point, and surely it can be enhanced. I prefered to develop as class so you could separate elaboration code from display code (you should just develop another class and instantiate it inside Gui's calc method). When you have to do the conversion you have to query self.radio"variable" to get user selected option. If you need further help, please ask. I'll try to answer as soon as possible.
from Tkinter import *
class Calculate:
def __init__(self):
self.stuff = None #store here cosstants to do conversions...
def convert1(self,startval):#,someother params to specify "from" and "to"):
return startval#this is an identity just as example
def convert2(self,startval):
pass
#...and so on...
class Gui:
def __init__(self):
self.root = Tk()
self.c = Calculate()
self.volumef = StringVar()
self.volumef.set("C")
self.volumet = StringVar()
self.volumet.set("C")
self.weightf = StringVar()
self.weightf.set("K")
self.weightt = StringVar()
self.weightt.set("K")
self.distancef = StringVar()
self.distancef.set("M")
self.distancet = StringVar()
self.distancet.set("M")
self.temperaturef = StringVar()
self.temperaturef.set("C")
self.temperaturet = StringVar()
self.temperaturet.set("C")
self.f3 = None
self.f4 = None
self.f5 = None
self.DISTANCEMODES = [("Meter", "M"),
("Km", "K"),
("Feet", "F")
]
self.VOLUMEMODES = [ ("cm^3","C"),
("m^3","M"),
("mm^3","MM")
]
self.TEMPERATUREMODE = [ ("Celsius","C"),
("Farenheit","H"),
("Kelvin","K")
]
self.WEIGHTMODE = [ ("Kg","K"),
("g","G"),
("mg","M")
]
self.root.title("Conversions")
self.f1 = Frame(self.root,relief=SUNKEN)
self.f1.pack()
self.createWidgets()
self.root.mainloop()
def createWidgets(self):
self.f1 = Frame(self.root)
self.bd = Button(self.f1, text="Distance",command=self.distance,width=10)
self.bd.pack(side=LEFT,padx=10,pady=10)
self.bw = Button(self.f1, text="Weight",command=self.weight,width=10)
self.bw.pack(side=LEFT,padx=10,pady=10)
self.f1.pack()
self.f2 = Frame(self.root)
self.bt = Button(self.f2, text="Temperature",command=self.temperature,width=10)
self.bt.pack(side=LEFT,padx=10,pady=10)
self.bv = Button(self.f2, text="Volume",command=self.volume,width=10)
self.bv.pack(side=LEFT,padx=10,pady=10)
self.f2.pack()
def convert(self,val):
var = self.edit1.get()#get value
if val==0:#choose what conversion applay
#x = self.c.convert1(var,self.volumef,self.volumet)
x = self.c.convert1(var)#do a conversion
print "volume calc"
elif val==1:
x = self.c.convert1(var)#do a conversion
print "weight calc"
elif val==2:
x = self.c.convert1(var)#do a conversion
print "distance calc"
elif val==3:
x = self.c.convert1(var)#do a conversion
print "temperature calc"
else:
print "it should never happen, but u can trow an excepion"
x=0 #to avoid a python s.f. as I don't trow/manage exceptions
self.edit2.config(state=NORMAL)#set as normal to be able to edit
self.edit2.delete(0,END)#delete previous content
self.edit2.insert(0,x)#add new content
self.edit2.config(state=DISABLED)#do not allow user input
def createRadio(self,fv,tv,cmdp,mode):#fromvariable,tovariable,commandparam,mode
if self.f3 and self.f4 and self.f5:
self.f3.pack_forget()
self.f4.pack_forget()
self.f5.pack_forget()
#FROM:
self.f3 = Frame(self.root)
lbl = Label(self.f3,text="From:",width=8)
lbl.pack(side=LEFT)
for m_text,m_mode in mode:
b = Radiobutton(self.f3,text=m_text,value=m_mode,variable=fv)
b.pack(side=LEFT)
self.edit1 = Entry(self.f3,width=10)
self.edit1.pack(side=LEFT)
self.f3.pack()
#TO:
self.f4 = Frame(self.root)
lbl = Label(self.f4,text="To:",width=8)
lbl.pack(side=LEFT)
for m_text,m_mode in mode:
b = Radiobutton(self.f4,text=m_text,value=m_mode,variable=tv)
b.pack(side=LEFT)
self.edit2 = Entry(self.f4,width=10)
self.edit2.config(state=DISABLED)
self.edit2.pack(side=LEFT)
self.f4.pack()
self.f5 = Frame(self.root)
self.btnCalc = Button(self.f5,text="Calc",command=lambda:self.convert(cmdp),width=10)
self.btnCalc.pack()
self.f5.pack()
def volume(self):
self.createRadio(self.volumef,self.volumet,0,self.VOLUMEMODES)
def weight(self):
self.createRadio(self.weightf,self.weightt,1,self.WEIGHTMODE)
def distance(self):
self.createRadio(self.distancef,self.distancet,2,self.DISTANCEMODES)
def temperature(self):
self.createRadio(self.temperaturef,self.temperaturet,3,self.TEMPERATUREMODE)
Gui()
[EDIT]: ok i fixed a bit my code, now it should have a bit more sense ;)
Related
I'm trying to make a small tkinter program to calculate the area of shapes and volumes
and I've made a main py file "area_volume_calculator.py" and two libraries "area.py" and "volume.py"
The main program's radio buttons work fine, but when I create the second window from Area_calculator I can't seem to get radio buttons to work properly. When it opens, the last 2 radio buttons are selected already.
I can still select an option but self.choice.get() always returns the default value which is -1, I don't know how to get it to work.
Can anyone help me get the radio buttons to work properly?
Any and all help is appreciated
Main Program:
from tkinter import *
from area import *
# from volume import *
class Menu:
def __init__(self):
self.window = Tk()
self.window.title("Areas and Volumes")
# self.name_label = Label(self.window, text = "Name: ")
# self.name_label.grid(row=0,column=0)
# self.name_entry = Entry(self.window)
# self.name_entry.grid(row=0,column=1)
# self.age_label = Label(self.window, text = "Age: ")
# self.age_label.grid(row=1,column=0)
# self.age_entry = Entry(self.window)
# self.age_entry.grid(row=1,column=1)
self.choice = IntVar()
self.area_radiobutton = Radiobutton(self.window, text = "Area Calculator", var = self.choice, value = 0)
self.area_radiobutton.grid(row=2,column=0)
self.volume_radiobutton = Radiobutton(self.window, text = "Volume Calculator", var = self.choice, value = 1)
self.volume_radiobutton.grid(row=3,column=0)
self.choice.set(-1)
self.submit_button = Button(self.window, text = "Submit", command = self.submit)
self.submit_button.grid(row=4,column=0)
print(self.choice.get())
self.window.mainloop()
def submit(self):
print(self.choice.get())
if self.choice.get() == 0:
area_calculator = Area_calculator()
# elif self.choice.get() == 1:
# volume_calculator = Volume_calculator()
menu = Menu()
area.py library:
from tkinter import *
class Area_calculator():
def __init__(self):
self.window = Tk()
self.window.title
self.window.title("Area Calculator")
self.choice_label = Label(self.window, text = "Choose a shape")
self.choice_label.grid(row=0,columnspan=1)
self.choice = IntVar()
self.rectangle_radiobutton = Radiobutton(self.window, text = "Rectangle", var = self.choice, value = 0)
self.rectangle_radiobutton.grid(row=1,column=0)
self.triangle_radiobutton = Radiobutton(self.window, text = "Triangle", var = self.choice, value = 1)
self.triangle_radiobutton.grid(row=2,column=0)
self.circle_radiobutton = Radiobutton(self.window, text = "Circle", var = self.choice, value = 2)
self.circle_radiobutton.grid(row=3,column=0)
self.submit_button = Button(self.window, text = "Submit", command = self.submit)
self.submit_button.grid(row=4,column=0)
self.choice.set(-1)
print(self.choice.get())
self.window.mainloop()
def submit(self):
print(self.choice.get())
# if self.choice.get() == 0:
# rectangle_calculator = Rectangle_calculator()
# elif self.choice.get() == 1:
# triangle_calculator = Triangle_calculator()
# elif self.choice.get() == 2:
# circle_calculator = Circle_calculator()
You are creating two instances of tk.Tk() (one in each class) which is never a good idea. tk.Tk() does not just create a new window but also a new embedded Tcl interpreter and this can mess things up, particularly IntVars and other variables such as self.choice. For more information see here.
If you want to have multiple windows then use tk.Toplevel() instead.
In answer to your second question in the comments, you must first add the parameters name and age to the __init__ of the Area_calculator class, and also pass them to the class when creating it in Menu.
Completed code:
Main program:
from tkinter import *
from area import *
class Menu:
def __init__(self):
self.window = Tk()
self.window.title("Areas and Volumes")
self.name_label = Label(self.window, text = "Name: ")
self.name_label.grid(row=0,column=0)
self.name_entry = Entry(self.window)
self.name_entry.grid(row=0,column=1)
self.age_label = Label(self.window, text = "Age: ")
self.age_label.grid(row=1,column=0)
self.age_entry = Entry(self.window)
self.age_entry.grid(row=1,column=1)
self.choice = IntVar()
self.area_radiobutton = Radiobutton(self.window, text = "Area Calculator", var = self.choice, value = 0)
self.area_radiobutton.grid(row=2,column=0)
self.volume_radiobutton = Radiobutton(self.window, text = "Volume Calculator", var = self.choice, value = 1)
self.volume_radiobutton.grid(row=3,column=0)
self.choice.set(-1)
self.submit_button = Button(self.window, text = "Submit", command = self.submit)
self.submit_button.grid(row=4,column=0)
print(self.choice.get())
self.window.mainloop()
def submit(self):
print(self.choice.get())
if self.choice.get() == 0:
name = self.name_entry.get()
age = self.age_entry.get()
area_calculator = Area_calculator(name, age)
menu = Menu()
area.py library:
from tkinter import *
class Area_calculator():
def __init__(self, name, age):
self.window = Toplevel()
self.window.title
self.window.title("Area Calculator")
self.name_label = Label(self.window, text = f"{name=}", width=10)
self.name_label.grid()
self.age_label = Label(self.window, text = f"{age=}", width=10)
self.age_label.grid(row=0, column=1)
self.choice_label = Label(self.window, text = "Choose a shape")
self.choice_label.grid(row=1,columnspan=1)
self.choice = IntVar()
self.rectangle_radiobutton = Radiobutton(self.window, text = "Rectangle", var = self.choice, value = 0)
self.rectangle_radiobutton.grid(row=2,column=0)
self.triangle_radiobutton = Radiobutton(self.window, text = "Triangle", var = self.choice, value = 1)
self.triangle_radiobutton.grid(row=3,column=0)
self.circle_radiobutton = Radiobutton(self.window, text = "Circle", var = self.choice, value = 2)
self.circle_radiobutton.grid(row=4,column=0)
self.submit_button = Button(self.window, text = "Submit", command = self.submit)
self.submit_button.grid(row=5,column=0)
self.choice.set(-1)
print(self.choice.get())
self.window.mainloop()
def submit(self):
print(self.choice.get())
Another noob asking for help again. Here is my code. I am trying to collect my text from the textbox. I have searched for the solution on how to save it but it just opens the save file and doesn't save anything. What I am trying to do is to save the text into a file after I've listed data using my widgets as a save file but sadly, that's the only thing that does not work for me. Perhaps I did something wrong in trying to save it. I am trying to fix my function saving_file_txt.
class OrderWindow:
def __init__(self, master):
self.master = master
self.master.title("Order Window Page")
self.master.geometry("1500x800")
self.master.configure(background="azure")
self.frame = Frame(self.master)
self.frame.pack()
# Placeholder for the information when ordering
self.prod_no_var = StringVar() # Product No input placeholder
self.product_name_var = StringVar() # Product Name input placeholder
self.quantity_var = StringVar() # Quantity input placeholder
self.prod_cost_var = StringVar() # Product Cost input placeholder
self.subtotal_var = StringVar() # Subtotal input placeholder
######################### Ordering Frame ################################
# Frame 1 - Ordering Details
self.order_detail_frame = Frame(self.frame, bg="azure")
self.order_detail_frame.grid(row=1, column=0)
self.basket_frame = Frame(self.frame)
self.basket_frame.grid(row=1, column=1)
self.heading = Label(self.order_detail_frame, text="AAT Shopping Application",
font=("arial", 15, "bold")).grid(row=0, column=0, ipadx=25)
self.order_detail_lblFrame = LabelFrame(self.order_detail_frame, text="Order Details")
self.order_detail_lblFrame.grid(row=1, column=0, ipady=50)
self.basket_heading = Label(self.basket_frame,
text="Product No\t\tProduct Name\t\tProduct Quantity\t\tProduct Price\t\tSubtotal"
).grid(row=0, column=0, columnspan=4, sticky="ne", ipadx=10)
self.basket_textbox = Text(self.basket_frame)
self.basket_textbox.grid(row=1, column=0, columnspan=4)
###########################Labels#############################
self.order_no = Label(self.order_detail_lblFrame, text="Order No").grid(row=0, column=0)
self.prod_name_lbl = Label(self.order_detail_lblFrame, text="Product Name").grid(row=1, column=0)
self.prod_qty_lbl = Label(self.order_detail_lblFrame, text="Quantity").grid(row=2, column=0)
self.prod_cost_lbl = Label(self.order_detail_lblFrame, text="Product Cost").grid(row=3, column=0)
self.subtotal_lbl = Label(self.order_detail_lblFrame, text="Sub Total").grid(row=4, column=0)
# Entry and Option Menu for ordering
########################### Product Combo Box #############################
self.prod_name_cb = ttk.Combobox(self.order_detail_lblFrame, textvariable=self.product_name_var)
self.prod_name_cb.grid(row=1, column=1, padx=35)
self.prod_name_cb["value"] = ("", "Gundam", "Starwars", "Paw Patrol", "Peppa Pig", "Cars Disney", "Teddy Bear")
self.prod_name_cb.current(0)
########################## Entry Box #############################
self.prod_no_entry = Entry(self.order_detail_lblFrame, textvariable=self.prod_no_var)
self.prod_no_entry.grid(row=0, column=1)
self.order_qty_entry = Entry(self.order_detail_lblFrame, textvariable=self.quantity_var)
self.order_qty_entry.grid(row=2, column=1)
self.order_cost_entry = Entry(self.order_detail_lblFrame, textvariable=self.prod_cost_var, state="disabled")
self.order_cost_entry.grid(row=3, column=1)
self.order_subtotal_entry = Entry(self.order_detail_lblFrame, textvariable=self.subtotal_var,
state="disabled")
self.order_subtotal_entry.grid(row=4, column=1) # Repeated line because it returns none value which gives error
########################## Buttons #############################
self.add_button = Button(self.order_detail_lblFrame, text="Add", command=self.add_item).grid(row=6, column=0)
self.delete_button = Button(self.order_detail_lblFrame, text="Delete", command=self.delete_item).grid(row=7,
column=0)
self.reset_button = Button(self.order_detail_lblFrame, text="Reset", command=self.reset_entry).grid(row=8,
column=0)
self.category_button = Button(self.order_detail_lblFrame, text="View products",
command=self.open_catalogue).grid(row=9, column=0)
self.save_basketfile_button = Button(self.order_detail_lblFrame, text="Save Reciept",
command=self.saving_file_txt
).grid(row=6, column=1)
self.pay_button = Button(self.order_detail_lblFrame, text="Checkout",
command=self.checkout_item).grid(row=7, column=1)
self.screenshot_button = Button(self.order_detail_lblFrame, text="Screenshot Window",
command=self.screenshoot_screen).grid(row=8, column=1)
self.exit_window_button = Button(self.order_detail_lblFrame, text="Exit",
command=self.exit_window).grid(row=9, column=1)
def add_item(self):
global total
item_dict = {"": 0, "Gundam": 10, "Starwars": 20, "Paw Patrol": 30, "Peppa Pig": 15, "Cars Disney": 15,
"Teddy Bear": 10}
order_no = self.prod_no_var.get()
item = self.product_name_var.get()
price = (self.prod_cost_var.get())
qty = int(self.quantity_var.get())
for product, cost in item_dict.items():
if item == product:
price = cost
total = round(price * qty, 2)
self.prod_no_var.set(int(order_no) + 1)
self.prod_cost_var.set("£" + str(price))
self.subtotal_var.set("£" + str(total))
self.basket_textbox.insert(END, self.prod_no_var.get() + "\t\t" + self.product_name_var.get() + "\t\t\t" +
self.quantity_var.get() + "\t\t" + self.prod_cost_var.get() + "\t\t" +
self.subtotal_var.get() + "\n")
def delete_item(self):
self.basket_textbox.delete("1.0", "2.0")
def reset_entry(self):
self.prod_no_var.set("")
self.product_name_var.set("")
self.quantity_var.set("")
self.prod_cost_var.set("")
self.subtotal_var.set("")
def checkout_item(self):
self.newWindow = Toplevel(self.master)
self.app = PaymentWindow(self.newWindow)
def open_catalogue(self):
self.newWindow = Toplevel(self.master)
self.app = CatalogueWindow(self.newWindow)
def exit_window(self):
self.master.destroy()
def screenshoot_screen(self):
window_screenshot = pyautogui.screenshot()
file_path = filedialog.asksaveasfilename(defaultextension=".png")
window_screenshot.save(file_path)
def saving_file_txt(self):
filetext = self.basket_textbox.get("1.0", "end-1c")
save_text = filedialog.asksaveasfilename(
defaultextension="txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
)
filetext.save(save_text)
I too am a newb , but this seems crazy confusing to utilize a class for a new window in tkinter.
Maybe try to simplify by utilizing tkinter.Toplevel() and then sourcing your logical functions from there. eliminate the need for so many self calls and just update forms after submission and save. A simplified example below.
# import libraries (i use as tk to reduce the full import on launch)
import tkinter as tk
client_orders = [] # List of orders
def new_order_popup():
new_order_window.deiconify() # used to open the new order window (toplevel window)
class NEW_ORDER: # new order class, simplified for example)
def __init__(self, product_num, product_name, product_price):
self.product_num = product_num
self.product_name = product_name
self.product_price = product_price
def new_order(product_num, product_name, product_price): # creates each new order when
called.
new_order_window.deiconify()
input_product_num = pro_num_entry.get()
input_product_name = pro_name_entry.get()
input_product_price = float(pro_price_entry.get())
newOrder = NEW_ORDER(input_product_num, input_product_name, input_product_price)
return newOrder
def sub_(): # action when button pressed for submit/save
customer_order = new_order(product_num=str, product_name=str, product_price=float)
price_str = str(customer_order.product_price)
client_orders.append(customer_order)
order_string = (customer_order.product_num,' : ', customer_order.product_name,' :
', price_str,'\n')
print(order_string)
txt_file = open(f'text_doc.txt', 'a')
txt_file.writelines(order_string)
txt_file.close()
def sub_ex(): # same as other button but closes toplevel window.
customer_order = new_order(product_num=str, product_name=str, product_price=float)
price_str = str(customer_order.product_price)
client_orders.append(customer_order)
order_string = (customer_order.product_num, ' : ', customer_order.product_name, '
: ', price_str, '\n')
print(order_string)
txt_file = open(f'text_doc.txt', 'a')
txt_file.writelines(order_string)
txt_file.close()
new_order_window.withdraw()
#main window tkinter code. (at bottom eleviates complicated poiubters abd calls)
main = tk.Tk()
main.geometry('300x100')
main.title('Some Ordering System')
#button that does something
new_order_button = tk.Button(main)
new_order_button.configure(text='NewOrder', command = lambda: new_order_popup())
new_order_button.pack(pady=25)
#secondary window
new_order_window = tk.Toplevel(main)
new_order_window.geometry('300x200')
new_order_window.withdraw()
list_label = tk.Label(new_order_window)
list_label.configure(text='Prod. Num.\nProd. Name.\nProd. Price.')
list_label.place(anchor=tk.NW, x=15, y=15)
pro_num_entry = tk.Entry(new_order_window)
pro_num_entry.configure(width=20)
pro_num_entry.place(anchor=tk.NW, x=100, y=15)
pro_name_entry = tk.Entry(new_order_window)
pro_name_entry.configure(width=20)
pro_name_entry.place(anchor=tk.NW, x=100, y=35)
pro_price_entry = tk.Entry(new_order_window)
pro_price_entry.configure(width=20)
pro_price_entry.place(anchor=tk.NW, x=100, y=55)
submit_button = tk.Button(new_order_window)
submit_button.configure(text='Submit', command = lambda: sub_())
submit_button.place(anchor=tk.NW, x=35, y=100)
submit_exit_button = tk.Button(new_order_window)
submit_exit_button.configure(text='Submit and exit', command = lambda: sub_ex())
submit_exit_button.place(anchor=tk.NW, x=100, y=100)
main.mainloop()
launch: (mainwindow)
click:(toplevel)
output:(txt_file)
Hope this helps a bit. sometimes the answer is in the nested mess with my projects.
There is no save() function for string (filetext). You need to open the selected file (save_text) in write mode and save the text content to the file:
def saving_file_txt(self):
filetext = self.basket_textbox.get("1.0", "end-1c")
save_text = filedialog.asksaveasfilename(
defaultextension="txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
)
if save_text:
with open(save_text, "w") as f:
f.write(filetext)
There's no save() method that can be used to save data; instead, you have to "manually" save the data. You can use the following commands to save the data:
open(filename, 'w').write(data)
I am losing my peanuts here. I am trying to clear two label values but i get an error
AttributeError: 'Label' object has no attribute 'delete'
basically if i were to click the calculate subtotal button then click the divide total button. I get my intended values. Now if I were to click on the clear values button i get an error. Literally shaking my head as I type this. Anyone care to explain why this is the case?
try:
import Tkinter as tk
except:
import tkinter as tk
class GetInterfaceValues():
def __init__(self):
self.root = tk.Tk()
self.totalValue = tk.StringVar()
self.root.geometry('500x200')
self.calculateButton = tk.Button(self.root,
text='Calculate Subtotal',
command=self.getSubtotals)
self.divideTotalButton = tk.Button(self.root,
text='Divide total',
command=self.divide)
self.textInputBox = tk.Text(self.root, relief=tk.RIDGE, height=1, width = 6, borderwidth=2)
self.firstLabel = tk.Label(self.root, text="This is the subtotal:")
self.secondLabel = tk.Label(self.root, text="This is the Divide Total:")
self.clearTotalButton = tk.Button(self.root, text='clear the values',command = self.clear)
self.firstLabel.pack(side="bottom")
self.secondLabel.pack(side="bottom")
self.textInputBox.pack()
self.calculateButton.pack()
self.divideTotalButton.pack()
self.clearTotalButton.pack()
self.root.mainloop()
def getTextInput(self):
result = self.textInputBox.get("1.0", "end")
return result
def getSubtotals(self):
userValue = int(self.getTextInput())
self.firstLabel["text"] = self.firstLabel["text"] + str(userValue * 5)
def divide(self):
userValue = int(self.getTextInput())
self.secondLabel["text"] = self.secondLabel["text"] + str(userValue / 10)
def clear(self):
self.firstLabel["text"] = self.firstLabel.delete("1.0","end")
app = GetInterfaceValues()
try:
import Tkinter as tk
except:
import tkinter as tk
class GetInterfaceValues():
def __init__(self):
self.root = tk.Tk()
self.totalValue = tk.StringVar()
self.root.geometry('500x200')
self.calculateButton = tk.Button(self.root,
text='Calculate Subtotal',
command=self.getSubtotals)
self.divideTotalButton = tk.Button(self.root,
text='Divide total',
command=self.divide)
self.textInputBox = tk.Text(self.root, relief=tk.RIDGE, height=1, width = 6, borderwidth=2)
self.firstLabelDefault = "This is the subtotal:"
self.secondLabelDefault = "This is the Divide Total:"
self.firstLabel = tk.Label(self.root, text=self.firstLabelDefault)
self.secondLabel = tk.Label(self.root, text=self.secondLabelDefault)
self.clearTotalButton = tk.Button(self.root, text='clear the values',command = self.clear)
self.firstLabel.pack(side="bottom")
self.secondLabel.pack(side="bottom")
self.textInputBox.pack()
self.calculateButton.pack()
self.divideTotalButton.pack()
self.clearTotalButton.pack()
self.root.mainloop()
def getTextInput(self):
result = self.textInputBox.get("1.0", "end")
return result
def getSubtotals(self):
userValue = int(self.getTextInput())
self.firstLabel["text"] = self.firstLabel["text"] + str(userValue * 5)
def divide(self):
userValue = int(self.getTextInput())
self.secondLabel["text"] = self.secondLabel["text"] + str(userValue / 10)
def clear(self):
self.firstLabel["text"] = self.firstLabelDefault
self.secondLabel["text"] = self.secondLabelDefault
self.textInputBox.delete("1.0", "end")
app = GetInterfaceValues()
You may have confused the methods of tkinter.Text and tkinter.Label. The method you called was tkinter.label.delete, which is not defined (does not exist), however it does exist for the tkinter.Text. Therefore, the only way to 'reset' would be to change the text attribute of the tkinter.Labels back to a 'default' string. It would perhaps be more appropriate to use another widget instead.
I just started coding less than 3 weeks ago (took a class in Lynda) and now working on a GUI that enable user to tick/untick a lists. I manage to get it done but in inefficient workaround (someone gave me a heads up on this).
What i have done basically calling a variables for each checkbox and insert the checkbox states into it. So if I have 100 of checkboxes in the list, I will need to create 100 variables. Below is the working code that I wrote.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
var1t1 = tk.IntVar()
var2t1 = tk.IntVar()
var3t1 = tk.IntVar()
var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")
def boxstates_t1():
var_name = [var1t1.get(), var2t1.get(), var3t1.get()]
print(var_name)
# -----------------Checkbox-----------------
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
check1_t1 = ttk.Checkbutton(root, text = "Mike", variable = var1t1)
check1_t1.pack(anchor = tk.W)
check2_t1 = ttk.Checkbutton(root, text = "Harry", variable = var2t1)
check2_t1.pack(anchor = tk.W)
check3_t1 = ttk.Checkbutton(root, text = "Siti", variable = var3t1)
check3_t1.pack(anchor = tk.W)
# -----------------Button-----------------
btn2 = ttk.Button(root, text="Show", command = boxstates_t1)
btn2.pack(side=tk.RIGHT)
root.mainloop()
Then i googled around and found few code that lead me to use for loop to print the list. I initialize the var_name = [] so that it will capture each checkbox state from the list.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
var1 = tk.IntVar()
var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")
def boxstates():
var_name = var1.get()
print(var_name)
# ------------------Chekbox-------------
name1 = ["Mike", "Harry", "Siti"]
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
for checkboxname in name1:
check1_t1 = ttk.Checkbutton(root, text=checkboxname, variable=var1)
check1_t1.pack(anchor = tk.W)
# ------------------Button-------------
btn2 = ttk.Button(root, text="Show", command = boxstates)
btn2.pack(side=tk.RIGHT)
root.mainloop()
But I was unable to tick the checkbox independently and the print out result also comes back as if it's in single variable. Am I doing the array var_name = [] wrongly? I'm currently lost and have no clue where to head next.
Any advise is greatly appreciate.
Try this:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Testing Checkbox")
root.geometry("200x150")
def boxstates():
for var in vars:
print (var.get())
names = ["Mike", "Harry", "Siti"]
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
vars = []
for i, checkboxname in enumerate(names):
vars.append(tk.IntVar())
check = ttk.Checkbutton(root, text=checkboxname, variable=vars[i])
check.pack(anchor = tk.W)
btn = ttk.Button(root, text="Show", command = boxstates)
btn.pack(side=tk.RIGHT)
root.mainloop()
import tkinter as tk
from tkinter import ttk
def boxstates():
finalValue = []
for x in checkboxList:
finalValue.append(x.get())
print(finalValue)
root = tk.Tk()
root.title("Testing Checkbox")
root.geometry("200x150")
# ------------------Chekbox-------------
checkboxList = [tk.IntVar(), tk.IntVar(), tk.IntVar()] # if you want to add more you can either append to it or declare it before runtime
name1 = ["Mike", "Harry", "Siti"]
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
def createCheckboxes():
for x, y in zip (checkboxList, name1):
check1_t1 = ttk.Checkbutton(root, text=y, variable=x)
check1_t1.pack(anchor = tk.W)
# ------------------Button-------------
btn2 = ttk.Button(root, text="Show", command = boxstates)
btn2.pack(side=tk.RIGHT)
createCheckboxes()
root.mainloop()
Sorry for the mess
so I am making a seating chart, and I cant seem to get it working properly... again. I am trying to make the label reset every time i press the run button, any ideas?
#commands: add name , Run
#imports
import random
from time import sleep
from tkinter import *
#Console and background Handlers
Tables = 6
Names = []
def AddNames():
NewNames = e.get("1.0", 'end -1c')
if NewNames in Names:
print("Name Already exists")
elif NewNames == "":
print("Empty")
else:
Names.append(NewNames)
print(Names)
e.delete(1.0, END)
def Random():
RandomNum = random.randrange(Tables)
if RandomNum == 0:
RandomNum = random.randrange(Tables)
return RandomNum
def run():
X = 0
for i in Names:
#print(Names[X])
print("Table: " + str(Random()))
X += 1
#text = Label(popup, text = "")
text = Label(popup, text= Names[X] + "\n" + "Table: " + str(Random()))
text.pack()
#GUI Handler
root = Tk()
root.geometry("1024x768")
e = Text(root, bd = 10, font=("Comic Sans MS", 50) ,width = 15, height = 2)
e.pack()
popup = Toplevel()
popup.title("Seating Chart")
AddNameButton = Button(root, text = ("Add Name"), width = 15, height = 5, command = AddNames)
AddNameButton.pack()
RunButton = Button(root, text = ("Run"), width = 15, height = 5, command = run)
RunButton.pack()
root.mainloop()
I am trying to reset text every time the user presses the run button
import tkinter
from tkinter import ttk
import random
class MyApp:
def __init__(self):
self.root = tkinter.Tk()
self.seatwindow = None
self.root.title('Add Names')
self.currentname = tkinter.StringVar()
self._maxtables = tkinter.StringVar()
self.addednames = []
self.commandframe = ttk.Labelframe(self.root, text='Commands')
self.nameentry = ttk.Entry(self.root, textvariable=self.currentname)
self.addbutton = ttk.Button(self.root, text='Add Name', command=self.addname)
self.maxtablabel = ttk.Label(self.root, text='Tables: ')
self.maxtabentry = ttk.Entry(self.root, textvariable=self._maxtables)
self.genbutton = ttk.Button(self.commandframe, text='Run', command=self.generate)
self.resetbutton = ttk.Button(self.commandframe, text='Reset', command=self.reset)
self._maxtables.set('6')
self.nameentry.grid(row=0, column=0)
self.addbutton.grid(row=0, column=1, sticky='nsew')
self.maxtabentry.grid(row=1, column=1, sticky='nsw')
self.maxtablabel.grid(row=1, column=0, sticky='nse')
self.genbutton.grid(row=0, column=0, sticky='nsew')
self.resetbutton.grid(row=0, column=1, sticky='nsew')
self.commandframe.grid(row=2, column=0, columnspan=2, sticky='nsew')
self.nameentry.bind('<Return>', self.addname)
self.root.bind('<Control-Return>', self.generate)
def addname(self, event=None):
name = self.currentname.get()
if not(name == '' or name in self.addednames):
self.addednames.append(name)
self.currentname.set('')
else:
self.currentname.set('Name already added!')
def generate(self, event=None):
if not self.seatwindow == None:
self.seatwindow.destroy()
self.currentname.set('')
self.seatwindow = tkinter.Toplevel()
random.shuffle(self.addednames)
tables = []
for i in range(self.maxtables):
tableframe = ttk.Labelframe(self.seatwindow, text='Table ' + str(i + 1) + ':')
tableframe.grid(column=i, row=0, sticky='nsew')
tables.append(tableframe)
for index, name in enumerate(self.addednames):
namelabel = ttk.Label(tables[index%self.maxtables], text=name)
namelabel.grid(column=0, row=index//self.maxtables + 1)
def reset(self):
self.currentname.set('')
self.maxtables = 6
self.addednames = []
def run(self):
self.root.mainloop()
#property
def maxtables(self):
return int(self._maxtables.get())
MyApp().run()