prng,python, tkinter,need to change picture - python

I ran into this problem and don't know how to solve it.
When I press the "generate" button(self.gen), my picture 11 changes to picture 22.
BUT I need the image 11 to NOT change when the button is clicked and an error occurs(messagebox.showerror pops up) OR so that after closing the messagebox.showerror, picture 22 changes to 11
import tkinter
from tkinter import *
from tkinter import messagebox, scrolledtext
from PIL import Image, ImageTk
from random import randint
class App:
def __init__(self):
self.window = tkinter.Tk()
self.window.title("Генератор")
self.window['bg'] = '#FFF5EE'
self.window.geometry('660x550')
self.window.resizable(False,False)
self.lb1 = Label(self.window, text="Enter:", background='#FFF5EE', font = ("Comic Sans MS", 14))
self.lb1.grid(column=0, row=2)
self.lb2 = Label(self.window, text="min(1-999)",background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb2.grid(column=1, row=3)
self.lb3 = Label(self.window, text="max(1-999)", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb3.grid(column=1, row=4)
self.lb4 = Label(self.window, text="amount of numbers", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb4.grid(column=4, row=3)
self.txt2 = Entry(self.window,width=10, borderwidth=3)
self.txt2.grid(column=2, row=3)
self.txt3 = Entry(self.window,width=10, borderwidth=3)
self.txt3.grid(column=2, row=4)
self.txt4 = Entry(self.window,width=10, borderwidth=3)
self.txt4.grid(column=5, row=3)
self.scrolltxt = scrolledtext.ScrolledText(self.window, width=30, height=3, borderwidth=7, state='disabled')
self.scrolltxt.grid(row=1, column=2, columnspan=3, padx=10, pady=10)
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.gen = Button(self.window, width = 15, text="Generate", command = lambda:[self.clicked1(), self.gen1()])
self.gen.grid(row=4, column=6)
self.canvas = tkinter.Canvas(self.window, height=230, width=230)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw', image = self.photo)
self.btn = Button(self.window, width = 15, text="Delete", command=lambda:[self.delete(),self.clicked2()])
self.btn.grid(column=6, row=5)
self.exit = Button(self.window, width = 15, text="Exit", command=lambda: [self.clicked3(), quit()])
self.exit.grid(column=6, row=6)
self.i = Button(self.window, width = 8,text = "i", font = ("Eras Bold ITC", 10) , command = self.inf)
self.i.grid(row = 0,column = 6)
self.window.mainloop()
def clicked1(self):
print("clicked1")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\22.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box
else:
messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
def delete(self):
self.txt4.delete(0, END)
self.txt3.delete(0, END)
self.txt2.delete(0, END)
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.config(state="disabled") # disable the text box
def clicked2(self):
print("clicked2")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def clicked3(self):
messagebox.showinfo("Це Звірополіс. Будь-хто може бути будь-ким.", "Хто сказав, що неможливе недосяжне?! Пошкодуйте цього дивака.")
def inf(self):
messagebox.showinfo("Info", "Лисичка замахалась")
app = App()
is it possible to implement this through tkinter?

Change the command argument of self.gen to:
self.gen = Button(self.window, width = 15, text="Generate", command=self.gen1)
And move the call to clicked1() into the if block of gen1() so it will only be called when conditions are accepted
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror(
"Error",
"Якщо не рвешся у висоту, шишок не наб'єш."
)
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box
self.clicked1() # call the 'clicked1' method
else:
messagebox.showerror(
"Error",
"Якщо не рвешся у висоту, шишок не наб'єш."
)

Related

Python text box

I am trying to take input name, email and password from user and print it in screen. But the variable is took is showing none every time. Can anyone solve my problem?
import tkinter as tk
import tkinter.font as f
r = tk.Tk()
name=''
email=''
password=''
def Print():
print("Name is",name)
print("Email is",email)
print("Password is",password)
f=tk.Frame(r,height=600,width=900)
f.pack()
name = tk.Label(f, text = "Name").place(x = 30,y = 50)
email = tk.Label(f, text = "Email").place(x = 30, y = 90)
password = tk.Label(f, text = "Password").place(x = 30, y = 130)
sbmitbtn = tk.Button(f, text = "Submit",activebackground = "pink", activeforeground = "blue",command=lambda:[Print(),f.destroy()]).place(x = 30, y = 170)
e1 = tk.Entry(f,textvariable=name).place(x = 80, y = 50)
e2 = tk.Entry(f,textvariable=email).place(x = 80, y = 90)
e3 = tk.Entry(f,textvariable=password).place(x = 95, y = 130)
r.mainloop()
you can use StringVar to get the string. the textvariable in your Label needs to be a Tkinter variable, quote:
"
textvariable= Associates a Tkinter variable (usually a StringVar) to
the contents of the entry field. (textVariable/Variable)
you can read more here
import tkinter as tk
import tkinter.font as f
r = tk.Tk()
name = tk.StringVar()
email = tk.StringVar()
password = tk.StringVar()
def Print():
print("Name is", name.get())
print("Email is", email.get())
print("Password is", password.get())
f = tk.Frame(r, height=600, width=900)
f.pack()
tk.Label(f, text="Name").place(x=30, y=50)
tk.Label(f, text="Email").place(x=30, y=90)
tk.Label(f, text="Password").place(x=30, y=130)
sbmitbtn = tk.Button(f, text="Submit", activebackground="pink", activeforeground="blue",
command=lambda: [Print(), f.destroy()]).place(x=30, y=170)
e1 = tk.Entry(f, textvariable=name).place(x=80, y=50)
e2 = tk.Entry(f, textvariable=email).place(x=80, y=90)
e3 = tk.Entry(f, textvariable=password).place(x=95, y=130)
r.mainloop()

Printing tkinter label in new line

First of all, sorry for that vague title. I am making a python application that shows time, fetches weather and News. Now, when i print news through tkinter label, it prints the titles of news on a separate line but in the center. If I try to specify the .pack(side=LEFT) geometry, it goes to the left but all the headlines print in a string and not in a newline. I have tried adding new line by '\n' and even carriage return '\n' but in vain. Please help me out with this issue. Attaching the code below.
P.s i could not get it the news to work with the For loop so i manually printed arrays.
from tkinter import *
import datetime
from PIL import Image, ImageTk
import requests
class Clock(Frame):
def __init__(self, parent):
Frame.__init__(self,parent, bg='black')
self.now = datetime.datetime.today()
self.time = str(self.now.hour) + ":" + str(self.now.minute)
self.timelb = Label(self, text=self.time, font=("Helvetica 50"), bg='black', fg='white')
self.timelb.pack(anchor=NE,padx=60,pady=0)
self.date = str(self.now.day) + '.' + str(self.now.month) + '.' + str(self.now.year)
self.day = self.now.strftime('%A')
self.daylb = Label(self, text=self.day, font="Helvetica 20", bg='black', fg='white')
self.daylb.pack(anchor=NE,padx=60)
self.datelb = Label(self, text=self.date, font="Helvetica 25", bg = 'black', fg='white')
self.datelb.pack(anchor=NE, padx=60)
class Weather(Frame):
def __init__(self, parent):
Frame.__init__(self,parent,bg='black')
url = 'http://api.openweathermap.org/data/2.5/weather?appid=c73d9cdb31fd6a386bee66158b116cd0&q=Karachi&units=metric'
json = requests.get(url).json()
temperature = json['main']['temp']
description = json['weather'][0]['description']
icon_id = json['weather'][0]['icon']
city = 'Karachi'
icon_url = ('http://openweathermap.org/img/wn/{icon}#2x.png'.format(icon=icon_id))
self.im = Image.open(requests.get(icon_url, stream=True).raw)
self.ph = ImageTk.PhotoImage(self.im)
degree = u'\N{DEGREE SIGN}' + 'C'
self.pic_label = Label(self,image=self.ph,bg='black')
self.pic_label.pack()
self.lab= Label(self,text=(str(temperature) + degree),font=("Helvetica 40"), bg='black', fg='white')
self.lab.pack()
self.description_label=Label(self, text=description, font='Helvetica 20',bg='black', fg='white')
self.description_label.pack()
self.city_label=Label(self, text=city, font = 'Helvetica 10', bg='black', fg='white')
self.city_label.pack()
class News(Frame):
def __init__(self, parent):
super(News, self).__init__(bg='black')
url = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=caa7f97ce8f2400a9785cbe704afc345"
json = requests.get(url).json()
self.title = 'Headlines'
self.title_lb = Label(self, text=self.title, font='Helvetica 25',bg='black', fg='white')
self.title_lb.pack(side=TOP, anchor=N)
im = Image.open('Newspaper_reduced.png')
self.pho = ImageTk.PhotoImage(im)
news1 = json['articles'][0]['title']
news2 = json['articles'][1]['title']
news3 = json['articles'][2]['title']
news4 = json['articles'][3]['title']
news5 = json['articles'][4]['title']
self.img = Label(self,image=self.pho,bg='black')
self.img.pack(side=LEFT)
self.headline1_lb = Label(self, text=news1, font = 'Helvetica 15' ,bg='black', fg='white')
self.headline1_lb.pack(side=LEFT)
self.img2 = Label(self,image=self.pho,bg='black')
self.img2.pack(side=LEFT)
self.headline2_lb = Label(self, text = news2, font='Helvetica 15',bg='black', fg='white')
self.headline2_lb.pack(side=LEFT)
self.img3 = Label(self,image=self.pho,bg='black')
self.img3.pack(side=LEFT)
self.headlines3_lb = Label(self, text=news3, font='Helvetica 15',bg='black', fg='white')
self.headlines3_lb.pack(side=LEFT)
self.img4 = Label(self,image=self.pho,bg='black')
self.img4.pack(side=LEFT)
self.headlines4_lb = Label(self, text=news4, font='Helvetica 15',bg='black', fg='white')
self.headlines4_lb.pack(side=LEFT)
self.img5 = Label(self,image=self.pho,bg='black')
self.img5.pack(side=LEFT)
self.headlines5_lb = Label(self, text=news5, font='Helvetica 15',bg='black', fg='white')
self.headlines5_lb.pack(side=LEFT)
class Fullscreen:
def __init__(self):
self.tk = Tk()
self.tk.configure(bg='black')
self.tk.title('smartmirror')
self.topFrame = Frame(self.tk , bg='black')
self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
self.bottomFrame = Frame(self.tk, bg='black')
self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
self.clock = Clock(self.topFrame)
self.clock.pack(side=RIGHT, anchor=NE, padx=50, pady=60)
self.weather = Weather(self.topFrame)
self.weather.pack(side=LEFT, anchor=NW, padx=50, pady=70)
self.news = News(self.bottomFrame)
self.news.pack(side=BOTTOM, anchor=S)
if __name__ == '__main__':
w = Fullscreen()
w.tk.mainloop
First: I removed images in code because I don't have them and I want to waste time to search images which I could use as replacement.
If you set different color for labels then you see then have different width - they use width of text.
If you use
self.headline1_lb.pack(fill='x')
then they will use the same width but text still is in center.
If you use
Label(..., anchor='w')
then it will move text to left side.
If you will put in Label text with many lines then you may need also
Label(..., anchor='w', justify='left')
If you want use full width of window for text then you have to use fill='x'
self.news.pack(side=BOTTOM, anchor='s', fill='x')
After that you can again set black background.

Creating Tkinter Text boxes and inserting into a dictionary

I have a long chunk of code. I do not want to paste it all here, so let me explain what I am trying to accomplish here. Based on a number provided by the user I want to create that many text boxes and then get what is entered into that text box and insert that into the dictionary. I have tried this a few ways and just cannot get it to work correctly. The list is either empty or it only contains the last text box as the value for each key.
def multiple_choice():
def add():
top.destroy()
top = Tk()
top.title("Add Question")
w = 800
h = 800
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
question = Label(top, text="Question to be asked?", font = "Times 14 bold", fg = "blue")
question.grid(row = 2, column = 4)
questionText = Text(top, borderwidth = 5, width=50,height=5, wrap=WORD, background = 'grey')
questionText.grid(row = 3, column = 4)
numQuestions = Label(top, text = "Number of answer choices?", font = "Times 14 bold", fg = "blue")
numQuestions.grid(row = 4, column=4)
num = Entry(top, bd = 5)
num.grid(row=5, column = 4)
answerList = {}
def multiple():
def preview():
preview = Tk()
top.title("Question Preview")
w = 500
h = 500
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
title = Label(preview, text = "Short Answer Question Preview", font = "Times 18 bold", fg = "blue" )
title.grid(row = 0, column = 2)
qtext = "Question text will read: "
ques = Label(preview, text = qtext)
ques.grid(row=1, column = 2)
ques2 = Label( preview, text = questionText.get("1.0",END))
let = 'A'
i = 1
for word in answerList:
prev = let + ": " + word
ans = Label(preview, text = prev)
ans.grid(row=1+i, column = 2)
let = chr(ord(let) + 1)
answerCor = "The correct answer(s): "
a = Label(preview, text = answerCor)
a.grid(row=4, column = 2)
b = Label(preview, text = cor.get)
b.grid(row=5, column = 2)
if num.get().isdigit():
number = int(num.get())
AnswerChoices = Label(top, text = "Answer Choices?", font = "Times 14 bold", fg = "blue")
AnswerChoices.grid(row = 6, column=4)
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
print answerList
correct = Label(top, text = "Correct Answer(s) (seperated by commas)",
font = "Times 14 bold", fg = "blue")
correct.grid(row =99 , column=4)
cor = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
cor.grid(row=100, column = 4)
else:
error = Tk()
w = 500
h = 100
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
error.geometry('%dx%d+%d+%d' % (w, h, x, y))
text = "ERROR: You must enter an integer number"
Label(error,text = text, fg = "red", font = "Times 16 bold").pack()
MyButton5 = Button(top, text="Preview Question", width=20, command = preview, anchor=S)
MyButton5.grid(row=102, column=5)
MyButton4 = Button(top, text="Finish and Add Question", width=20, command = add, anchor=S)
MyButton4.grid(row=102, column=2)
but = Button(top, text="Submit", width=10, command = multiple)
but.grid(row=6, column = 4)
top.mainloop()
def button():
MyButton21 = Button(quiz, text="Short Answer Question", width=20, command = short_answer)
MyButton21.grid(row=8, column=2)
MyButton22 = Button(quiz, text="True/False Question", width=20, command = true_false)
MyButton22.grid(row=8, column=4)
MyButton23 = Button(quiz, text="Multiple Choice Question", width=20, command = multiple_choice)
MyButton23.grid(row=9, column=2)
#MyButton24 = Button(quiz, text="Matching Question", width=20, command = matching)
#MyButton24.grid(row=9, column=4)
MyButton25 = Button(quiz, text="Ordering Question", width=20, command =order)
MyButton25.grid(row=10, column=2)
MyButton26 = Button(quiz, text="Fill in the Blank Question", width=20, command = fill_blank)
MyButton26.grid(row=10, column=4)
MyButton3 = Button(quiz, text="Finsh Quiz", width=10, command = quiz)
MyButton3.grid(row=12, column=3)
quiz = Tk()
w = 700
h = 300
ws = quiz.winfo_screenwidth()
hs = quiz.winfo_screenheight()
x = 0
y = 0
quiz.geometry('%dx%d+%d+%d' % (w, h, x, y))
quiz.title("eCampus Quiz Developer")
L1 = Label(quiz, text="Quiz Title?")
L1.grid(row=0, column=0)
E1 = Entry(quiz, bd = 5)
E1.grid(row=0, column=3)
name_file = E1.get()
name_file = name_file.replace(" ", "")
name_file = name_file + ".txt"
with open(name_file,"w") as data:
MyButton1 = Button(quiz, text="Submit", width=10, command = button)
MyButton1.grid(row=1, column=3)
quiz.mainloop()
I am trying to create the dictionary using this chunk of code:
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
I have even tried putting a loop in the preview function but that is when the last box was the only value contained in the dictionary. Any ideas would be appreciated
Please see my commeneted snippet below which demonstrates this:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.entry = Entry(self.root) #entry to input number of entries later
self.button = Button(self.root, text="ok", command=self.command) #calls command to draw the entry boxes
self.frame = Frame(self.root)
self.entry.pack()
self.button.pack()
self.frame.pack()
def command(self):
self.frame.destroy() #destroys frame and contents
self.frame = Frame(self.root) #recreates frame
self.text = [] #empty array to store entry boxes
for i in range(int(self.entry.get())):
self.text.append(Entry(self.frame, text="Question "+str(i))) #creates entry boxes
self.text[i].pack()
self.done = Button(self.frame, text="Done", command=self.dict) #button to call dictionary entry and print
self.done.pack()
self.frame.pack()
def dict(self):
self.dict = {}
for i in range(len(self.text)):
self.dict.update({self.text[i].cget("text"): self.text[i].get()})
#the above line adds a new dict entry with the text value of the respective entry as the key and the value of the entry as the value
print(self.dict) #prints the dict
root = Tk()
App(root)
root.mainloop()
The above asks the user how many entry widgets they want to create, fills a frame with those entry widgets and then iterates through the list which contains them on the press of a button, adding a new dictionary entry for each entry widget, where the key of the dict is the attribute text for each entry and the value of the dict is the value of each entry.

How to fix this Tkinter button bug

Whenever I run the program, the buttons show up however the images do not show and instead appear as a grey space. Also, all the buttons apart from the 'finish' button are unpressable (see the image attached).
def NoFood():
TotalCalories = NoBreakfast.calories
NoFoodOption = 1
def BoiledEggsFunct():
TotalCalories = BoiledEggs.calories + TotalCalories
def FriedEggsFunct():
TotalCalories = FriedEggs.calories + TotalCalories
def ScrambledEggsFunct():
TotalCalories = ScrambledEggs.calories + TotalCalories
def PoachedEggsFunct():
TotalCalories = PoachedEggs.calories + TotalCalories
def ToastFunct():
TotalCalories = Toast.calories + TotalCalories
def BaconFunct():
TotalCalories = Bacon.calories + TotalCalories
def CerealFunct():
TotalCalories = Cereal.calories + TotalCalories
def PorridgeFunct():
TotalCalories = Porridge.calories + TotalCalories
def FinishScreen():
FinishWindow = Toplevel()
if TotalCalories > 0 and TotalCalories < 1000:
HealthyLabel = Label(FinishWindow, text = "Congratulations, you are healthy!", font=("Comic Sans MS", 25), fg = "light green",
bg = "black")
HealthyLabel.grid(columnspan=10)
elif TotalCalories > 1000:
UnhealthyLabel = Label(FinishWindow, text = "Try to eat healthier tomorrow. See personalised advice", font=("Comic Sans MS", 25), fg = "yellow",
bg = "black")
UnhealthyLabel.grid(columnspan=10)
elif NoFoodOption == 1:
NoFoodLabel = Label(FinishWindow, text = "Not eating can be harmful to your health. See personalised advice", font=("Comic Sans MS", 25), fg = "red",
bg = "black")
NoFoodLabel.grid(columnspan=10)
else:
Error = Label(FinishWindow, text = "error", font=("Comic Sans MS", 25), fg = "red",
bg = "black")
NoFoodLabel.grid(columnspan=10)
BoiledEggsPhoto = PhotoImage(file="BoiledEgg.gif")
BoiledEggsButton = Button(FoodSelectionWindow, text="Boiled Eggs", command=BoiledEggsFunct, image=BoiledEggsPhoto, compound=LEFT, height=100, width = 200)
BoiledEggsButton.grid(column=1,row=3)
ScrambledEggsPhoto = PhotoImage(file="ScrambledEgg.gif")
ScrambledEggsButton = Button(FoodSelectionWindow, text="Scrambled Eggs", command=ScrambledEggsFunct, image=ScrambledEggsPhoto, compound=LEFT, height=100, width = 200)
ScrambledEggsButton.grid(column=2,row=3)
FriedEggsPhoto = PhotoImage(file="FriedEgg.gif")
FriedEggsButton = Button(FoodSelectionWindow, text="Fried Eggs", command = FriedEggsFunct, image=FriedEggsPhoto, compound=LEFT, height=100, width = 200)
FriedEggsButton.grid(column=3, row=3)
PoachedEggsPhoto = PhotoImage(file="PoachedEgg.gif")
PoachedEggsButton = Button(FoodSelectionWindow, text="Poached Eggs", command = PoachedEggsFunct, image=PoachedEggsPhoto, compound=LEFT, height=100, width = 200)
PoachedEggsButton.grid(column=1, row=4)
ToastPhoto = PhotoImage(file="Toast.gif")
ToastButton = Button(FoodSelectionWindow, text="Toast", command = ToastFunct, image=ToastPhoto, compound=LEFT, height=100, width = 200)
ToastButton.grid(column=2,row=4)
BaconPhoto = PhotoImage(file="Bacon.gif")
BaconButton = Button(FoodSelectionWindow, text="Bacon", command = BaconFunct, image=BaconPhoto, compound=LEFT, height=100, width = 200)
BaconButton.grid(column=3, row=4)
CerealPhoto = PhotoImage(file="Cereal.gif")
CerealButton = Button(FoodSelectionWindow, text="Cereal", command = CerealFunct, image=CerealPhoto, compound=LEFT, height=100, width = 200)
CerealButton.grid(column=1, row=5)
PorridgePhoto = PhotoImage(file="Porridge.gif")
PorridgeButton = Button(FoodSelectionWindow, text="Porridge", command = PorridgeFunct, image=PorridgePhoto, compound=LEFT, height=100, width = 200)
PorridgeButton.grid(column=2, row=5)
NoBreakfastPhoto = PhotoImage(file="NoBreakfast.gif")
NoBreakfastButton = Button(FoodSelectionWindow, text= "None", command = NoFood, image=NoBreakfastPhoto, compound=LEFT, height=100, width = 200)
NoBreakfastButton.grid(column=3, row =5)
EndScreen = Button(FoodSelectionWindow, text="Finish", command = FinishScreen, width=12)
EndScreen.grid(column=2,row=6)
Any suggestions? Thanks.

Self is not defined?

I am attempting to make a basic study clock as a learning exercise for Tkinter but I get an error when attempting run it saying self is not defined. Here is the error message.
Traceback (most recent call last):
File "productivityclock.py", line 6, in <module>
class gui(object):
File "productivityclock.py", line 113, in gui
while 0 < self.z:
NameError: name 'self' is not defined
Here is my code, I would really appreciate if someone could help me out, Thanks
from Tkinter import *
import time
root = Tk()
class gui(object):
def __init__(self, master):
self.frame = Frame(master)
self.frame.pack()
t_int = 0
b_int = 0
reps = 0
self.menu()
def menu(self):
self.button1 = Button(
self.frame, text="Set Time", command = self.set_time)
self.button2 = Button(
self.frame, text="Set Breaks", command = self.set_break)
self.button3 = Button(
self.frame, text="Set Intervals", command = self.set_reps)
self.button4 = Button(
self.frame, text="Start", command = self.timer)
self.button1.pack(side = LEFT)
self.button2.pack(side = LEFT)
self.button3.pack(side = LEFT)
self.button4.pack(side = LEFT)
def set_time(self):
self.button1.pack_forget()
self.button2.pack_forget()
self.button3.pack_forget()
self.button4.pack_forget()
self.l = Label(self.frame, text = "Enter the time of each study session (minutes)")
self.button = Button(
self.frame, text="Get", command=self.on_button1)
self.entry = Entry(self.frame)
self.button.pack(side = RIGHT)
self.entry.pack(side = LEFT)
self.l.pack(side = LEFT)
def set_break(self):
self.button1.pack_forget()
self.button2.pack_forget()
self.button3.pack_forget()
self.button4.pack_forget()
self.l = Label(self.frame, text = "Enter the time of each break (minutes)")
self.button = Button(
self.frame, text="Get", command=self.on_button2)
self.entry = Entry(self.frame)
self.button.pack(side = RIGHT)
self.entry.pack(side = LEFT)
self.l.pack(side = LEFT)
def set_reps(self):
self.button1.pack_forget()
self.button2.pack_forget()
self.button3.pack_forget()
self.button4.pack_forget()
self.l = Label(self.frame, text = "Enter the amount of study sessions (minutes)")
self.button = Button(
self.frame, text="Get", command=self.on_button3)
self.entry = Entry(self.frame)
self.button.pack(side = RIGHT)
self.entry.pack(side = LEFT)
self.l.pack(side = LEFT)
def on_button1(self):
x = self.entry.get()
self.t_int = x
print self.t_int
self.button.pack_forget()
self.entry.pack_forget()
self.l.pack_forget()
self.menu()
def on_button2(self):
x = self.entry.get()
self.b_int = x
print self.b_int
self.button.pack_forget()
self.entry.pack_forget()
self.l.pack_forget()
self.menu()
def on_button3(self):
x = self.entry.get()
self.reps = x
print self.reps
self.button.pack_forget()
self.entry.pack_forget()
self.l.pack_forget()
self.menu()
def timer(self):
x = self.t_int
y = self.b_int
self.z = self.reps
while 0 < self.z:
while x > 0:
time.sleep(60)
n = Label(self.frame, text = "You have %r minutes left in your session") % x
n.pack(side = LEFT)
x = x - 1
n.pack_forget
while y > 0:
time.sleep(60)
self.e = Label(self.frame, text = "You have %r minutes left in your break") % y
self.e.pack(side = LEFT)
self.y = self.y - 1
self.e.pack_forget()
z = z - 1
x = self.t_int
y = self.b_int
app = gui(root)
root.mainloop()
Yes, at line 113, while 0 < self.z: is not properly indented, and all the lines below it.

Categories