Tkinter radiobuttons not selecting properly - python

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

Related

How can i erase contents in a Label?

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

Python treeview and grid

The problem is that when some objects are being created in the double click subroutine the grid goes messed up. The tree view expands a bit to the right and labels and buttons which are suppose to go in column 1 look like they are in column 3(went off button above tree view which is in column 3). Also when I try making a button it puts it above the tree view no matter its row.
Code:
from tkinter import *
import os
import datetime
import sqlite3
from tkinter.ttk import Combobox,Treeview,Scrollbar
class Application(Frame):
""" Binary to Decimal """
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
self.grid()
self.create_GUI()
def Quit(self):
self.master.destroy()
def create_GUI(self):
self.title_lbl = Label(self, text = "Students")
self.title_lbl.grid(row = 0, column = 2)
self.fn_lbl = Label(self, text = "First Name:")
self.fn_lbl.grid(row = 1 , column = 1)
self.fn_txt = Entry(self)
self.fn_txt.grid(row = 1, column = 2)
self.ln_lbl =Label(self, text = "Last Name:")
self.ln_lbl.grid(row = 2, column = 1)
self.ln_txt = Entry(self)
self.ln_txt.grid(row = 2, column = 2)
self.q_btn = Button(self, text = "Back",padx=80,pady=10, command = lambda: self.Quit)
self.q_btn.grid(row = 3, column = 0)
self.s_btn = Button(self, text = "search",padx=80,pady=10, command = lambda: self.search())
self.s_btn.grid(row = 3,column = 3)
self.tree = Treeview(self.master,height = 6)
self.tree["columns"] = ("StudentID","First Name","Last Name")#,"House Number", "Street Name", "Town Or City Name","PostCode","MobilePhoneNumber")
self.tree.column("StudentID",width = 20)
self.tree.column("First Name",width = 40)
self.tree.column("Last Name", width = 40)
## self.tree.column("House Number", width = 60)
## self.tree.column("Street Name", width = 60)
## self.tree.column("Town Or City Name", width = 60)
## self.tree.column("PostCode", width = 60)
## self.tree.column("MobilePhoneNumber", width = 60)
self.tree.heading("StudentID",text="StudentID")
self.tree.heading("First Name",text="First Name")
self.tree.heading("Last Name",text="Last Name")
## self.tree.heading("House Number",text="House Number")
## self.tree.heading("Street Name",text="Street Name")
## self.tree.heading("Town Or City Name",text="Town Or City Name")
## self.tree.heading("PostCode",text="PostCode")
## self.tree.heading("MobilePhoneNumber",text="MobilePhoneNumber")
self.tree["show"] = "headings"
yscrollbar = Scrollbar(self.master, orient='vertical', command=self.tree.yview)
xscrollbar = Scrollbar(self.master, orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=yscrollbar.set, xscroll=xscrollbar.set)
yscrollbar.grid(row=4, column=3, padx=2, pady=2, sticky=NS)
self.tree.grid(row=4,column=0,columnspan =5, padx=2,pady=2,sticky =NSEW)
self.tree.bind("<Double-1>",lambda event :self.OnDoubleClick(event))
def OnDoubleClick(self, event):
curItem = self.tree.focus()
contents =(self.tree.item(curItem))
StudentDetails = contents['values']
print(StudentDetails)
self.tStudentID=StringVar()
self.tFirstName = StringVar()
self.tLastName = StringVar()
self.tHouseNumber = StringVar()
self.tStreetName = StringVar()
self.tTownOrCityName = StringVar()
self.tPostCode = StringVar()
self.tEmail = StringVar()
self.tMobilePhoneNumber = StringVar()
self.tStudentID.set(StudentDetails[0])
self.tFirstName.set(StudentDetails[1])
self.tLastName.set(StudentDetails[2])
self.tHouseNumber.set(StudentDetails[3])
self.tStreetName.set(StudentDetails[4])
self.tTownOrCityName.set(StudentDetails[5])
self.tPostCode.set(StudentDetails[6])
self.tEmail.set(StudentDetails[7])
self.tMobilePhoneNumber.set(StudentDetails[8])
self.inst_lbl0 = Label(self.master, text = "Student ID").grid(row=5,column=0,sticky=W)
self.NStudentID = Label(self.master, textvariable=self.tStudentID).grid(row =5,column=1,stick=W)
self.inst_lbl1 = Label(self.master, text = "First Name").grid(row=6,column=0,sticky=W)
self.NFirstName = Entry(self.master, textvariable=self.tFirstName).grid(row =6,column=1,stick=W)
self.inst_lbl2 = Label(self.master, text = "Last Name").grid(row=7,column=0,sticky=W)
self.NLastName = Entry(self.master, textvariable=self.tLastName).grid(row =7,column=1,stick=W)
self.inst_lbl3 = Label(self.master, text = "House Number").grid(row=8,column=0,sticky=W)
self.HouseNumber = Entry(self.master,textvariable=self.tHouseNumber).grid(row=8,column=1,sticky=W)
self.inst_lbl4 = Label(self.master, text = "Street Name").grid(row=9,column=0,sticky=W)
self.StreetName =Entry(self.master,textvariable=self.tStreetName).grid(row=9,column=1,sticky=W)
self.inst_lbl5 = Label(self.master, text = "Town or City Name").grid(row=10,column=0,sticky=W)
self.TownOrCityName =Entry(self.master,textvariable=self.tTownOrCityName).grid(row=10,column=1,sticky=W)
self.inst_lbl6 = Label(self.master, text = "Postcode").grid(row=11,column=0,sticky=W)
self.PostCode = Entry(self.master,textvariable=self.tPostCode).grid(row=11,column=1,sticky=W)
self.inst_lbl7 = Label(self.master, text = "Email").grid(row=12,column=0,sticky=W)
self.Email =Entry(self.master,textvariable=self.tEmail).grid(row=12,column=1,sticky=W)
self.inst_lbl8 = Label(self.master, text = "Mobile phonenumber").grid(row=13,column=0,sticky=W)
self.MobilePhoneNumber =Entry(self.master,textvariable=self.tMobilePhoneNumber).grid(row=13,column=1,sticky=W)
self.btnSaveChanges = Button(self, text = "save changes",padx=80,pady=10,command = lambda:self.SaveChanges).grid(row=14,column=0,sticky=W)
#self.btnSaveChanges = Button(self, text = "delete record",padx=80,pady=10,command = lambda:self.DeleteRecord).grid(row=14,column=1,sticky=W)
def search(self):
FirstName = self.fn_txt.get()
LastName = self.ln_txt.get()
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
cursor.row_factory = sqlite3.Row
sql = "select StudentID,FirstName,LastName,HouseNumber,StreetName,TownOrCityName,PostCode,Email,MobilePhoneNumber"\
" from tblStudents"\
" where FirstName like ?"\
" and LastName like ?"
cursor.execute(sql,("%"+FirstName+"%","%"+LastName+"%",))
StudentList = cursor.fetchall()
print(StudentList)
self.loadStudents(StudentList)
def loadStudents(self,StudentList):
for i in self.tree.get_children():
self.tree.delete(i)
for student in StudentList:
self.tree.insert("" , 0,values=(student[0],student[1],student[2],student[3],student[4],student[5],student[6],student[7],student[8]))
def SaveChanges(self):
with sqlite3.connect("GuitarLessons.db") as db:
cursor = db.cursor()
sql = "update tblStudents set FirstName =?,LastName=?,HouseNumber=?,StreetName=?,TownOrCityName=?,PostCode=?,Email=?,MobilePhoneNumber=? where StudentID=?"
cursor.execute(sql,("%"+NFirstName+"%","%"+NLastName+"%","%"+NHouseNumber+"%","%"+NStreetName+"%","%"+NTownOrCityName+"%","%"+NPostCode+"%","%"+NEmail+"%","%"+NMobilePhoneNumber+"%"))
db.commit()
def DeleteRecord(self):
print("")
root = Tk()
root.title("booking system")
root.geometry("800x800")
root.configure(bg="white")
app = Application(root)
root.mainloop()
The mistake you are making is that you're trying to put everything into one massive grid, but the code to populate that grid is scattered throughout your program. Your UI clearly has three distinct sections, you should organize your GUI that way.
Create a frame for the top, a frame for the treeview, and a frame for the bottom section. You can use pack to place these in the master window, one on top of the other. Then, place your other widgets in the appropriate frame. This way, changes you make in one section (adding or removing columns or rows, switching to pack, etc) won't affect the other areas.

Log in and Register button don't work (python, tkinter)

When i run it the two buttons show up but when i press 'Log In', This error shows:
inputDialog2 = LogIn(root)
TypeError: LogIn() takes no arguments (1 given)
and if i press 'Register', This error shows:
self.Label1 = Label(top, text = "What is your username: ")
AttributeError: Label instance has no __call__ method
This is my code:
from Tkinter import *
# User Registers an account with a username password and passwor retype.
class Main:
def __init__(self, parent):
top = self.top = Toplevel(parent)
self.Label = Label(top, text = 'Choose an option')
self.Label.grid(row = 0)
self.LoginB = Button(top, text = 'Log In', command = LogIn)
self.LoginB.pack()
self.RegisterB = Button(top, text = 'Register', command = launch_register)
self.RegisterB.pack()
Main().pack()
class Register:
def __init__(self, parent):
top = self.top = Toplevel(parent)
self.VarEntUser = StringVar()
self.VarEntPass = StringVar()
self.VarEntRetype = StringVar()
self.Label1 = Label(top, text = "What is your username: ")
self.Label2 = Label(top, text = "Enter a password: ")
self.Label3 = Label(top, text = "Retype Password: ")
self.EntUser = Entry(top, textvariable = self.VarEntUser )
self.EntPass = Entry(top, textvariable = self.VarEntPass)
self.EntRetype = Entry(top, textvariable = self.VarEntRetype)
self.Label1.grid(row = 0, sticky = W)
self.Label2.grid(row = 1, sticky = W)
self.Label3.grid(row = 2, sticky = W)
self.EntUser.grid(row = 0, column = 1)
self.EntPass.grid(row = 1, column = 1)
self.EntRetype.grid(row = 2, column = 1)
self.MySubmitButton = Button(top, text = 'Submit', command=RegisterCheck)
self.MySubmitButton.pack()
self.U = raw_input(self.VarEntUser.get())
self.P = raw_input(self.VarEntPass.get())
self.R = raw_input(self.VarEntRetype.get())
class LogIn:
def __init__(self, parent):
top = self.top = Toplevel(parent)
VarUserLog = StringVar()
VarPassLog = StringVar()
self.LabelUser = Label(top, text = 'Username:')
self.EntUserLog = Label(top, text = 'Password: ')
self.EntUserLog = Entry(top, textvariable = self.VarUserLog)
self.EntPassLog = Entry(top, textvariable = self.VarPassLog)
self.UserLog.grid(row = 1)
self.PassLog.grid(row = 2)
self.EntUserLog.grid(row = 1, column = 1)
self.EntPassLog.grid(row = 2, column = 1)
# runs the 'LoginCheck' function
self.LogInButton = Button(top, text = "Log In", command = LogInCheck)
self.User = raw_input(self.EntUserLog.get())
self.Pass = raw_input(self.EntUserLog.get())
# Checks the Log In details
def LogInCheck():
if len(self.User) <= 0 and len(self.Pass) <= 0:
print "Please fill in all fields."
else:
pass
if self.User in 'username.txt' and self.Pass in 'password':
print 'You are now logged in!'
else:
print "Log in Failed"
# Checks the password and checks if all fields have been entered
def RegisterCheck(self):
if len(self.P) <= 0 and len(self.U) <= 0:
print "Please fill out all fields."
else:
pass
if self.P == self.R:
pass
else:
print "Passwords do not match"
with open('username.txt', 'a') as fout:
fout.write(self.U + '\n')
with open('password.txt', 'a') as fout:
fout.write(self.P + '\n')
def launch_register():
inputDialog = Register(root)
root.wait_window(inputDialog.top)
def LogIn():
inputDialog2 = LogIn(root)
root.wait_window(inputDialog2.top)
# Main Window--
root = Tk()
Label = Label(root, text = 'Choose an option')
Label.pack()
LoginB = Button(root, text = 'Log In', command = LogIn)
LoginB.pack()
RegisterB = Button(root, text = 'Register', command = launch_register)
RegisterB.pack()
root.mainloop()
The mistakes in your program that cause these errors:
You start by declaring a class named LogIn; however you later create a function with the same name. Since the latter overrides the former, your method is called instead of your class constructor.
Similarly, in the line Label = Label(root, text = 'Choose an option') you assign a new meaning to the name Label, such that when you get to the line on which the second error occurs, the name Label does no longer refer to a class named Label, but instead an instance of that class.
Basically, you should use unique names for your variables, functions and classes (including names you import from modules such as Tkinter).

My window won't show up

Hi I am doing this Tkinter assignment and i don't know why it won't run even when i put the mainloop in it.
# Importing Tkinter to display the graphics
import Tkinter
# Creating a class called StoryMaker
class StoryMaker:
# The initializer with the self parameter
def __init__(self):
# This creates the main window
self.main_window = Tkinter.Tk()
# This creates the three different frames for different widgets
self.top_frame = Tkinter.Frame(self.main_window)
self.mid_frame = Tkinter.Frame(self.main_window)
self.bottom_frame = Tkinter.Frame(self.main_window)
# Instructs the user to enter the information given to create the story
self.story_label = Tkinter.Label (self.top_frame, text = "Please enter the information given for the new story, then click the \"Make Story\" Button!" )
self.prompt_label1 = Tkinter.Label (self.top_frame, text = "Character Name: ")
self.get_prompt1 = Tkinter.Entry (self.top_frame, width = 10)
self.story_label.pack (side = 'left')
story.prompt_label.pack (side = 'left')
self.get_prompt1.pack (side = 'left')
self.prompt_label2 = Tkinter.Label (self.mid_frame, text = "Place: ")
self.get_prompt2 = Tkinter.Entry (self.mid_frame, width = 10)
self.prompt_label3 = Tkinter.Label (self.mid_frame, text = "Food: ")
self.get_prompt3 = Tkinter.Entry (self.mid_frame, width = 10)
self.radio_var = Tkinter.IntVar()
self.radio_var.set(1)
self.prompt_label4 = Tkinter.Label(self.mid_frame, text = "Hotels")
self.rb1 = Tkinter.Radiobutton(self.mid_frame, text = "Hilton", variable = self.radio_var, value = 1)
self.rb2 = Tkinter.Radiobutton(self.mid_frame, text = "Burj Al Arab", variable = self.radio_var, value = 2)
self.rb3 = Tkinter.Radiobutton(self.mid_frame, text = "Holiday Inn", variable = self.radio_var, value = 3)
self.rb1.pack()
self.rb2.pack()
self.rb3.pcak()
self.cb_var1 = Tkinter.IntVar()
self.cb_var2 = Tkinter.IntVar()
self.cb_var3 = Tkinter.IntVar()
self.cb_var1.set(0)
self.cb_var2.set(0)
self.cb_var3.set(0)
self.prompt_label5 = Tkinter.Label (self.mid_frame, text = "Foods")
self.cb1 = Tkinter.Checkbutton (self.top_frame, text = "Pizza", variable = self.cb_var1)
self.cb2 = Tkinter.Checkbutton (self.top_frame, text = "Spaghetti", variable = self.cb_var2)
self.cb3 = Tkinter.Checkbutton (self.top_frame, text = "Hamburger", variable = self.cb_var3)
self.cb1.pack()
self.cb2.pack()
self.cb3.pack()
self.create_button = Tkinter.Button(self.bottom_frame, text = "Create", command = self.story)
self.quit_button = Tkinter.Button(self.bottom_frame, text = "Quit", command = self.main_window.quit)
self.create_button.pack(side = 'left')
self.quit_button.pack(side = 'left')
self.top_frame.pack()
self.mid_frame.pack()
self.bottom_frame.pack()
Tkinter.mainloop()
my_gui = StoryMaker
You last line should actually call the class you just spent all that time constructing:
my_gui = StoryMaker()
See how that works for you. Doing this will execute the special __init__() method, and run your GUI.

Radiobutton not working properly in python

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

Categories

Resources