I am a fairly novice programmer and through coffee, google, and an immense loss of hair and fingernails have managed to write a very messy code. I am asking anyone to help me simplify the code if possible.
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
one = 0
why = 'Total Number: {}'
no = 0
clack = 0
click = 'Clicks: {}'
s = ttk.Style()
s.theme_use('clam')
s.configure('red.Vertical.TProgressbar', foreground = 'red', background = 'red')
s.configure('green.Vertical.TProgressbar', foreground = 'green', background = 'green')
s.configure('TButton', relief = 'groove')
def iround(x):
y = round(x) - .5
return int(y) + (y > 0)
class Application(ttk.Frame):
def __init__(self, master = None):
ttk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def Number(self):
global one
cost = 10*(self.w['to'])
if self.number['text'] == "Make Number go up":
self.number['text'] = one
if iround(self.w.get()) == 0:
one += 1
else:
one += iround(self.w.get())
self.number['text'] = one
if self.number['text'] >= cost:
self.buy['state'] = 'normal'
else:
self.buy['state'] = 'disabled'
self.number['text'] >= cost
self.progress['value'] = one
if self.number['text'] >= cost:
self.progress['style'] = 'red.Vertical.TProgressbar'
else:
self.progress['style'] = 'green.Vertical.TProgressbar'
def Buy(self):
global one
self.w['to'] += 1
cost = 10*(self.w['to'])
one = self.number['text'] = (one + 10 - cost)
self.buy['text'] = ('+1 to slider | Cost: {}'.format(cost))
if self.number['text'] < (cost):
self.buy['state'] = 'disabled'
self.progress['value'] = one
self.progress['maximum'] += 10
if self.number['text'] >= cost:
self.progress['style'] = 'red.Vertical.TProgressbar'
else:
self.progress['style'] = 'green.Vertical.TProgressbar'
def scaleValue(self, event):
self.v['text'] = 'Slider Bonus + ' + str(iround(self.w.get()))
def clicks(self, event):
global click
global clack
if self.Clicks['text'] == 'Clicks: 0':
clack += 1
self.Clicks['text'] = click.format(clack)
self.Clicks['text'] = click.format(clack)
clack += 1
def NumberVal(self, event):
global why
global no
if self.fun['text'] == "Total Number: 0":
self.fun['text'] = why.format(no)
if iround(self.w.get()) == 0:
no += 1
else:
no += iround(self.w.get())
self.fun['text'] = why.format(no)
def createWidgets(self):
self.number = Button(self, text = 'Make number go up', command = self.Number, width = 20, style = 'TButton')
self.number.grid(row = 1, column = 1)
self.number.bind('<ButtonRelease>', self.clicks, add = '+')
self.number.bind('<ButtonRelease>', self.NumberVal, add = '+')
self.buy = Button(self, text = '+1 to Slider | Cost: 10', command = self.Buy, width = 20, style = 'TButton')
self.buy.grid(row = 2, column = 1)
self.buy.config(state = 'disabled')
self.v = Label(self, text = 'Slider Bonus + 0', width = 20, anchor = 'center')
self.v.grid(row = 3, column = 3)
self.w = Scale(self, from_ = 0, to = 1, orient = 'horizontal')
self.w.grid(row = 3, column = 1)
self.w.bind('<Motion>', self.scaleValue)
self.progress = Progressbar(self, value = 0, orient = 'vertical', maximum = 10, mode = 'determinate')
self.progress.grid(row = 1, rowspan = 5, column = 2)
self.Clicks = Label(self, text = 'Clicks: 0', width = 20, anchor = 'center')
self.Clicks.grid(row = 1, column = 3)
self.fun = Label(self, text = 'Total Number: 0', width = 20, anchor = 'center')
self.fun.grid(row = 2, column = 3)
app = Application()
app.master.title('Number')
app.mainloop()
Related
Okay so I wrote this code...
#!/usr/bin/env
import sys
import time
import subprocess
from Tkinter import *
import numpy
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
import matplotlib.pyplot as plt
import threading
CDatei = subprocess.Popen("/home/pi/meinc++/Spi")
print("Hallo")
i = 0
x = 0
def GetValue():
with open("/home/pi/meinc++/BeispielDatei.txt","r") as Datei:
for line in Datei:
time.sleep(0.01)
return line
def WithoutNull(input):
ReturnValue = input
while ReturnValue is None:
ReturnValue = GetValue()
return ReturnValue
def UebergabeWert():
while x == 0:
WholeString = WithoutNull(GetValue())
StringVar, DatumVar = WholeString.strip().split(' - ')
IntStringVar = [int(v) for v in StringVar.split()]
return IntStringVar, DatumVar
def MinutenWert():
Maximum = 0
Minimum = 0
i = 0
LaengeArray = 0
Multiplikator = 10000
ArrayValue = [-999999]*Multiplikator
AlteZeit = time.time()
while 1:
CompleteValue, Trash = UebergabeWert()
ArrayValue[i] = CompleteValue[0]
i = i + 1
ArrayFilter = filter(lambda c: c != -999999,ArrayValue)
ArraySumme = numpy.sum(ArrayFilter)
LaengeArray = len(ArrayFilter)
Mittelwert = ArraySumme/LaengeArray
ArraySortierung = sorted(ArrayFilter)
Maximum = ArraySortierung[LaengeArray-1]
Minimum = ArraySortierung[0]
NeueZeit = time.time()
if NeueZeit-AlteZeit >= 60:
AlteZeit = time.time()
ArrayValue[i:Multiplikator] = [-999999]*(Multiplikator-i)
i = 0
yield Mittelwert
yield Maximum
yield Minimum
yield LaengeArray
yield ArrayFilter
def UebergabeTkinter():
while 1:
Mittelwert = next(MinutenWertYield)
Maximum = next(MinutenWertYield)
Minimum = next(MinutenWertYield)
LaengeArray = next(MinutenWertYield)
ArrayFilter = next(MinutenWertYield)
CompleteValue, DatumVar = UebergabeWert()
Variable1.set(CompleteValue[0])
Variable2.set(CompleteValue[1])
Variable3.set(CompleteValue[2])
Variable4.set(CompleteValue[3])
VariableMittelwert.set(Mittelwert)
VariableMaximum.set(Maximum)
VariableMinimum.set(Minimum)
t = threading.Thread(target = Grafik)
t.start()
root.update()
def Grafik():
GrafikAnfang = time.time()
Array = 0
ArrayGrafik = [0]*20
GrafikEnde = 1
while 1:
CompleteValue, DatumVar = UebergabeWert()
ArrayGrafik[Array] = CompleteValue[0]
LaengeArrayGrafik = len(ArrayGrafik)
fig = Figure(figsize = (3, 3))
axis = fig.add_subplot(111)
axis.legend()
axis.grid()
canvas = FigureCanvasTkAgg(fig, master = root)
canvas.get_tk_widget().grid(row=10,column=0,rowspan=2,columnspan=2)
LinienBreite = numpy.linspace(1,LaengeArrayGrafik,LaengeArrayGrafik)
axis.plot(LinienBreite,ArrayGrafik,'b-')
axis.set_xticks(LinienBreite)
DatumArray = [DatumVar]
axis.set_xticklabels(DatumArray)
canvas.draw()
fig.clear()
print Array
if GrafikEnde-GrafikAnfang < 600:
Array = Array + 1
GrafikEnde = time.time()
if GrafikEnde-GrafikAnfang >= 600:
del ArrayGrafik[0]
def Exit():
root.destroy()
return
try:
MinutenWertYield = MinutenWert()
root = Tk()
Leiste = Menu(root)
root.config(menu = Leiste)
DateiMenu = Menu(Leiste)
Leiste.add_cascade(label = "datei", menu = DateiMenu)
DateiMenu.add_command(label = "Exit", command = Exit)
EditMenu = Menu(Leiste)
Leiste.add_cascade(label = "edit", menu = EditMenu)
Variable1 = IntVar()
Variable2 = IntVar()
Variable3 = IntVar()
Variable4 = IntVar()
VariableMittelwert = IntVar()
VariableMaximum = IntVar()
VariableMinimum = IntVar()
Ausgang = 0
for column in range(0,8,2):
String1 = "Ausgang "
String1 += `Ausgang`
Ausgang = Ausgang + 1
Label(text = String1).grid(row=0,column=column)
Ausgang = 0
for column in range(0,8,2):
String1 = "Der Wert von "
String2 = " ist: "
String1 += `Ausgang`
Ausgang = Ausgang + 1
String3 = String1+String2
Label(text = String3).grid(row=2,column=column)
Label(text = "Der Mittelwert ist: ").grid(row=4,column=0)
Label(text = "Das Maximum ist: ").grid(row=5,column=0)
Label(text = "Das Mimimum ist: ").grid(row=6,column=0)
Label1 = Label(root, textvariable = Variable1)
Label1.grid(row = 2, column = 1)
Label2 = Label(root, textvariable = Variable2)
Label2.grid(row = 2, column = 3)
Label3 = Label(root, textvariable = Variable3)
Label3.grid(row = 2, column = 5)
Label4 = Label(root, textvariable = Variable4)
Label4.grid(row = 2, column = 7)
LabelMittelwert = Label(root, textvariable = VariableMittelwert)
LabelMittelwert.grid(row = 4, column = 1)
LabelMaximum = Label(root, textvariable = VariableMaximum)
LabelMaximum.grid(row = 5, column = 1)
LabelMinimum = Label(root, textvariable = VariableMinimum)
LabelMinimum.grid(row = 6, column = 1)
UebergabeTkinter()
print "Hallo"
root.mainloop()
except KeyboardInterrupt:
CDatei.kill()
root.quit()
root.destroy()
and when i run it, it says "RuntimeError: main thread is not in the main loop".
Short explanation of the code: It's a code to read out sensor data from a text file -
GetValue().
If the Data is Null it'll read out again - WithoutNull().
The Data is then splitted into data and timestamp (cause it has the format val1, val2, val3, val4, time) - UebergabeWert.
Then the maxima, minima and average of the data will be measured - MinutenWert()
After this, the values are set as labels and go their way into Tkinter - UebergabeTkinter()
The Tkinter build is mainly in Try:
What I wanted to do there, is to implement a graph to Tkinter, but because of the fast changing values it got tremendously slow so i decided to put the graph build in a thread and run it parallel to Tkinter. Unfortunately, it doesn't seem to work and I don't know why
Any suggestions?
At first, I was suggested to differentiate between two codes under the name operation..so, I change the self.operation into self.operation1. After that I get another error self.operatio1_pending and I was suggested to introduce the self.operation_pending in init(). However I still get another error.
Here is the written codes with a hashtags to let you know where I have done the changes (and I added operation="" in init() since it gave me an error for not defined) Note: I also changed all self.operation in different methods into self.operation1.
from Tkinter import*
class Calculator():
def __init__ (self):
self.total = 0
self.current = ""
self.newnumber = True
self.operation1 = ""#
self.operation1_pending = False#
operation = ""#
self.equal = False
def PressedNumber(self, number):
self.equal = False
t = text_box.get()
n = str(number)
if self.newnumber:
self.current = n
self.newnumber = False
else:
if n == '.':
if n in t:
return
self.current = t + n
self.Display(self.current)
def TotalCalculated(self):
self.equal = True
self.current = float(self.current)
if self.operation1_pending == True:
self.calc_sum()
else:
self.total = float(text_box.get())
def Display(self, value):
text_box.delete(0, END)
text_box.insert(0, value)
def calc_sum(self):
if self.operation1 == "subtract":
self.total -= self.current
if self.operation1 == "add":
self.total += self.current
if self.operation1 == "divide":
self.total /= self.current
if self.operation1 == "multiply":
self.total *= self.current
self.newnumber = True
self.operation1_pending = False
self.Display(self.total)
def operation(self, operation1):
self.current = float(self.current)
if self.operation1_pending:
self.calc_sum()
elif not self.equal:
self.total = self.current
self.newnumber = True
self.operation1_pending = True
self.operation1 = operation
self.equal = False
def cancel(self):
self.equal = False
self.current = "0"
self.Display(0)
self.newnumber = True
def Cancelation_forEverything(self):
self.cancel()
self.total = 0
def sign(self):
self.equal = False
self.current = -(float(text_box.get()))
self.Display(self.current)
summ = Calculator()
root = Tk()
Calculator = Frame(root)
Calculator.grid()
root.title("Calculator")
root.configure(bg="Khaki")
root.minsize(width=220, height=20)
root.resizable(width=FALSE, height= FALSE)
text_box = Entry(Calculator, justify=RIGHT)
text_box.grid(row = 0, column = 0, columnspan=3, pady = 8, sticky=W+E)
text_box.insert(0, "0")
Numbers = "789456123"
a = 0
bttn = []
for r in range(1,4):
for c in range(3):
bttn.append(Button(Calculator, text = Numbers[a], font="Candara,20"))
bttn[a].grid(row = r, column = c, padx= 15, pady = 15)
bttn[a]["command"] = lambda x = Numbers[a]: summ.PressedNumber(x)
a += 1
bttn_0 = Button(Calculator, text = " 0 ", font="Candara,20")
bttn_0["command"] = lambda: summ.PressedNumber(0)
bttn_0.grid(columnspan = 5, sticky=N+W, padx= 20, pady = 20)
bttn_division = Button(Calculator, text = chr(247), font="Candara,20")
bttn_division["command"] = lambda: summ.operation("divide")
bttn_division.grid(row = 1, column = 3, pady = 10)
bttn_multiply = Button(Calculator, text = "x", font="Candara,20")
bttn_multiply["command"] = lambda: summ.operation("multiply")
bttn_multiply.grid(row = 2, column = 3, sticky=N, pady = 10)
bttn_subtract = Button(Calculator, text = "-", font="Candara,20")
bttn_subtract["command"] = lambda: summ.operation("subtract")
bttn_subtract.grid(row = 3, column = 3, pady = 10)
bttn_point = Button(Calculator, text = ".", font="Candara,20")
bttn_point["command"] = lambda: summ.PressedNumber(".")
bttn_point.grid(row = 4, column = 1, padx = 10, pady = 10)
bttn_addition = Button(Calculator, text = "+", font="Candara,20")
bttn_addition["command"] = lambda: summ.operation("add")
bttn_addition.grid(row = 4, column = 3, pady = 10)
bttn_neg = Button(Calculator, text = "+/-", font="Candara,20")
bttn_neg["command"] = summ.sign
bttn_neg.grid(row = 5, column = 0, pady = 10)
clear = Button(Calculator, text = "C", font="Candara,20")
clear["command"] = summ.cancel
clear.grid(row = 5, column = 1, pady = 10)
all_clear = Button(Calculator, text = "AC", font="Candara,20")
all_clear["command"] = summ.Cancelation_forEverything
all_clear.grid(row = 5, column = 2, pady = 10)
equals = Button(Calculator, text = "=", font="Candara,20")
equals["command"] = summ.TotalCalculated
equals.grid(row = 5, column = 3, pady = 10)
root.mainloop()
And here is the error message I now get:
Exception in Tkinter callback
Traceback (most recent call last):
File "Q:\Python.001\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "\\centre-fsrv07\SSHome$\352767933\Grade 10 CS\Working progress\Tkinter\Calculator4.py", line 110, in <lambda>
bttn_multiply["command"] = lambda: summ.operation("multiply")
File "\\centre-fsrv07\SSHome$\352767933\Grade 10 CS\Working progress\Tkinter\Calculator4.py", line 60, in operation
self.operation1 = operation
NameError: global name 'operation' is not defined
Please help me with what I need to change with fully explanation and codes...If you know other ways to get the calculator work without the given codes please suggest them and I'll be grateful.
From your code:
def operation(self, operation1):
self.current = float(self.current)
if self.operation1_pending:
self.calc_sum()
elif not self.equal:
self.total = self.current
self.newnumber = True
self.operation1_pending = True
self.operation1 = operation # <-- You mean operation1
self.equal = False
Change
self.operation1 = operation
To
self.operation1 = operation1
To reflect your method's parameter.
from tkinter import *
import tkinter.messagebox
from ProjectHeader import *
class Gui(object):
def __init__(self, parent):
self.gui = parent
self.gui.geometry("350x200")
self.gui.title("Converter")
self.checked1 = IntVar()
self.checked2 = IntVar()
self.c1 = Radiobutton(self.gui, text='(1)Centimeters', variable=self.checked1, value = 1)
self.c2 = Radiobutton(self.gui, text='(2)Meter', variable=self.checked1, value = 2)
self.c3 = Radiobutton(self.gui, text='(3)Millimeters', variable=self.checked1, value = 3)
self.c4 = Radiobutton(self.gui, text='(4)Kilometers', variable=self.checked1, value = 4)
self.c5 = Radiobutton(self.gui, text='(5)Centimeters', variable=self.checked2, value = 5)
self.c6 = Radiobutton(self.gui, text='(6)Meter', variable=self.checked2, value = 6)
self.c7 = Radiobutton(self.gui, text='(7)Millimeters', variable=self.checked2, value = 7)
self.c8 = Radiobutton(self.gui, text='(8)Kilometers', variable=self.checked2, value = 8)
self.b1 = Button(self.gui, text="Convert", command=self.callback)
self.l1 = Label(self.gui, text="Value")
self.l2 = Label(self.gui, text="Convert ->")
self.e1 = Entry(self.gui, bd = 5)
self.e1.insert(0, "0")
self.c1.pack(side = BOTTOM)
self.c2.pack(side = BOTTOM)
self.c3.pack(side = BOTTOM)
self.c4.pack(side = BOTTOM)
self.c5.pack(side = BOTTOM)
self.c6.pack(side = BOTTOM)
self.c7.pack(side = BOTTOM)
self.c8.pack(side = BOTTOM)
self.l1.pack(side = TOP)
self.l2.pack(side = TOP)
self.e1.pack(side = TOP)
self.b1.pack(side = TOP)
self.c1.place(x = 3, y = 90)
self.c2.place(x = 3, y = 110)
self.c3.place(x = 3, y = 130)
self.c4.place(x = 3, y = 150)
self.c5.place(x = 235, y = 90)
self.c6.place(x = 235, y = 110)
self.c7.place(x = 235, y = 130)
self.c8.place(x = 235, y = 150)
self.l2.place(x = 140, y = 110)
def callback(self):
if self.e1.get() == "0":
messagebox.showinfo("Error", "Please enter a value")
elif self.checked1.get(): #Centiemters
C = Centimeters(self.e1.get())
if self.checked2.get():
messagebox.showinfo("Error", "Converting the same unit!")
if self.checked2.get():
value = C.ToMeters()
messagebox.showinfo("Value", str(value) + ' cm')
if self.checked2.get():
value = C.ToMillimeters()
messagebox.showinfo("Value", str(value) + ' cm')
if self.checked2.get():
value = C.ToKilometers()
messagebox.showinfo("Value", str(value) + ' cm')
root = Tk()
my_window = Gui(root)
root.mainloop()
so now I changed the self.checked1.get() == 1 to self.checked1.get()
because you said by checking on the radiobutton, it would select the option
but now, when I the check the (1)Centimeters button, or either (5)Centimeters to (8)Kilometers button, the program would select all the options
for example, if I checked (1)Centimeters button and (8)Kilometers, the program would pop up not only converted value of Kilometers, but also the converted value of meters, millimeters.
so my question is how can I fix the program that when I checked the 1st box on the left side, and either one of the boxes on the right side, the program would give the correct selection?
Here is the interface of checkedbutton
http://postimg.org/image/6uqwkybw5/
If I understand what you want correctly, you should use the following code. Use self.checked1.get() to see what is the original unit and use self.checked2.get() to see to which unit it has to be converted.
if self.e1.get() == "0":
messagebox.showinfo("Error", "Please enter a value")
elif self.checked1.get() == 1: #Centimeters
C = Centimeters(self.e1.get())
if self.checked2.get() == 5:
messagebox.showinfo("Error", "Converting the same unit!")
if self.checked2.get() == 6:
value = C.ToMeters()
messagebox.showinfo("Value", str(value) + ' m')
if self.checked2.get() == 7:
value = C.ToMillimeters()
messagebox.showinfo("Value", str(value) + ' mm')
if self.checked2.get() == 8:
value = C.ToKilometers()
messagebox.showinfo("Value", str(value) + ' km')
I need to know how to implement the selected radio button into my calculations. Thanks for any and all help! I'm really not positive what the problem is, my only quest really comes from the "def selection" part. I just don't know what to do there
from Tkinter import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.headerFont = ("Times", "16", "italic")
self.title("Restaurant Tipper")
self.addOrigBill()
self.addChooseOne()
self.addPercTip()
self.addRateTip()
self.addOutput()
def addOrigBill(self):
Label(self, text = "Bill Amount",
font = self.headerFont).grid(columnspan = 1)
self.txtBillAmount = Entry(self)
self.txtBillAmount.grid(row = 1, column = 1)
self.txtBillAmount.insert(0,"100.00")
def addChooseOne(self):
Label(self, text = "Pick ONE! Choose your % of Tip or Rate your experience",
font = self.headerFont).grid(row = 2, column = 1)
def addPercTip(self):
Label(self, text = "% of Tip",
font = self.headerFont).grid(row = 3, column = 0)
self.radPercTip1 = Radiobutton(self, text = "15%",
variable = self.percVar, value = .15, command = self.selected)
self.radPercTip2 = Radiobutton(self, text = "17%",
variable = self.percVar, value = .17, command = self.selected)
self.radPercTip3 = Radiobutton(self, text = "20%",
variable = self.percVar, value = .20, command = self.selected)
self.radPercTip1.grid(row = 4, column = 0)
self.radPercTip2.grid(row = 5, column = 0)
self.radPercTip3.grid(row = 6, column = 0)
def selected(self):
float(self.percVar.get())
def addRateTip(self):
Label(self, text = "Tip by rating").grid(row = 3, column = 3)
Label(self, text = "1 being the worst").grid(row = 4, column = 3)
Label(self, text = "10 being the best").grid(row = 5, column = 3)
Label(self, text = "Experience").grid(row = 6, column = 2)
self.txtExperience = Entry(self)
self.txtExperience.grid(row = 6, column = 3)
def addOutput(self):
self.btnCalc = Button(self, text = "Calculate Tip")
self.btnCalc.grid(row = 7, columnspan = 2)
self.btnCalc["command"] = self.calculate
Label(self, text = "Tip").grid(row = 8, column = 1)
self.lblTip = Label(self, bg = "#ffffff", anchor = "w", relief = "ridge")
self.lblTip.grid(row = 8, column = 2, sticky = "we")
Label(self, text = "Total Bill").grid(row = 9, column = 1)
self.lblTotalBill = Label(self, bg = "#ffffff", anchor = "w", relief = "ridge")
self.lblTotalBill.grid(row = 9, column = 2, sticky = "we")
def calculate(self):
bill = float(self.txtBillAmount.get())
percTip = self.percVar
rateTip = int(self.addRateTip.get())
tip = bill * percTip
self.lblTip["text"] = "%.2f" % tip
totalBill = tip + bill
self.lblTotalBill["text"] = "%.2f" % totalBill
if rateTip <= 2:
percTip = .10
elif 3 <= rateTip <= 4:
percTip = .12
elif 5 <= rateTip <= 6:
percTip = .15
elif 7 <= rateTip <= 8:
percTip = .17
elif 9 <= rateTip <= 10:
percTip = .20
else:
self.lblTotalBill["text"] = "Something is wrong"
def main():
app = App()
app.mainloop()
if __name__ == "__main__":
main()
There is no self.percVar in your code. As #wastl said, you need to initialize it.
To do that, you need to use one of the variable classes. Since you are using float type, DoubleVar() would be the best.
def addPercTip(self):
self.percVar = DoubleVar() #this line should be added in your method
Label(self, text = "% of Tip",
font = self.headerFont).grid(row = 3, column = 0)
def selected(self):
print (type(self.percVar.get()))
#which is float, without converting explicitly because of DoubleVar()
print (self.percVar.get())
#this will print what you click
You forgot to intialize the self.percVar variable
Add self.percVar = 0 as the first line of the addPercTip method. That should fix your error.
BTW: For future questions the best thing is to include the error message you get and EXACTLY describe what part of the programm causes what kind of trouble for you
I'm writing a program that draws a rectangle or oval in a top frame depending on whether or not the user selects it via a radiobutton. There is a check button that determines whether the oval is filled as well. Both buttons are on the bottom frame. But for some reason when I run the code, it displays the window, but not the buttons themselves. How do I fix this?
Here's my code:
from tkinter import *
class GeometricFigures:
def __init__(self):
self.window = Tk()
self.window.title("Radiobuttons and Checkbuttons")
self.canvas = Canvas(self.window, width = 300, height = 100, bg = "white")
self.canvas.pack()
def drawButtons(self):
self.bottomframe = Frame(self.window)
self.bottomframe.pack()
self.check = IntVar()
cbtFilled = Checkbutton(self.bottomframe, variable = self.check, value = 0,
text = "Filled", command = self.processCheckbutton).pack(side = LEFT)
self.radio = IntVar()
rbRectangle = Radiobutton(self.bottomframe, variable = self.radio, value = 1,
text = "Rectangle", command = self.processRadiobutton.pack())
rbOval = Radiobutton(self.bottomframe, text = "Oval", variable = self.radio,
value = 2, command = self.processRadiobutton.pack())
cbtFilled.grid(row = 1, column = 2)
rbRectangle.grid(row = 1, column = 3)
rbOval.grid(row = 1, column = 4)
def processCheckbutton(self):
print("The check button is " +
("checked " if self.check.get() == 1 else "unchecked"))
def processRadiobutton(self):
print(("Rectangle" if self.radio.get() == 1 else "Oval")
+ " is selected ")
def drawRect(self):
self.canvas.create_rectangle(30, 10, 270, 60, tags = "rect")
def drawFillOval(self):
self.canvas.create_oval(30, 10, 270, 60, fill = 'blue', tags = "oval")
def drawOval(self):
self.canvas.create_oval(30, 10, 270, 60, tags = "oval")
def main(self):
test = GeometricFigures()
if self.check.get() == 1:
test.drawFillOval()
if self.radio.get() == 1:
test.drawRect()
else:
test.drawOval()
test.drawButtons()
if __name__ == '__main__':
main()
Thanks!