failed to resolve some method of tkinter - python

I am creating 2048 game on python with tkinter but I have a issue
I don't know what is wrong in left, right, up and down methods created in PageOne class.
In another class (StartPage), bind function calls these methods but this don't work
So I don't know how toresolve the mistakes, in bind functions or in the left, right, up and down methods?
In particular I get this error when I press the right key:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\fabio\PycharmProjects\2048gametk\2048gametk.py", line 198, in right
self.reverse()
AttributeError: 'Event' object has no attribute 'reverse'
And similar error for the other key (up, left and down):
Traceback (most recent call last):
File "C:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\fabio\PycharmProjects\2048gametk\2048gametk.py", line 208, in up
self.transpose()
AttributeError: 'Event' object has no attribute 'transpose'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
TypeError: PageOne.left() missing 1 required positional argument: 'event'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\fabio\PycharmProjects\2048gametk\2048gametk.py", line 218, in down self.transpose()
AttributeError: 'Event' object has no attribute 'transpose'
The left one is different because i put event instead of event = None as argument in the left module.
A small problem concern the score_frame that appears also in the StartPage and not only in the PageOne, so i don't know how to combine the frames on the code
Below you can find the entire code
Can anyone help me?
Thanks in advance
import os
import random
import sys
import tkinter as tk
from math import floor
class MyButton(tk.Button):
def __init__(self, *args, **kwargs):
tk.Button.__init__(self, *args, **kwargs, bg='brown', fg='white',
font="Helvetica 12 bold", width=8, pady='1m')
self.pack(pady="3m")
class Game(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("2048 game")
self.dim = 4
self.main_grid = None
container = tk.Frame(self, width=500, height=600)
container.grid(pady=(100, 0))
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
self.bind("<Left>", PageOne.left)
self.bind("<Right>", PageOne.right)
self.bind("<Up>", PageOne.up)
self.bind("<Down>", PageOne.down)
self.mainloop()
def show_frame(self, controller): #page_name al posto di controller
frame = self.frames[controller]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.dim = controller.dim
label = tk.Label(self, text="2048", font="Helvetica 48 bold", fg="orange")
label.pack(side="top", fill="x")
button1 = MyButton(self, text="3x3", command=self.dim_3)
button1.pack()
button1.bind("<Return>", self.dim_3)
button2 = MyButton(self, text="4x4", command=self.dim_4)
button2.focus_force()
button2.pack()
button2.bind("<Return>", self.dim_4)
button3 = MyButton(self, text="5x5", command=self.dim_5)
button3.pack()
button3.bind("<Return>", self.dim_5)
button4 = MyButton(self, text="8x8", command=self.dim_8)
button4.pack()
button4.bind("<Return>", self.dim_8)
def dim_3(self):
self.dim = 3
self.controller.show_frame(PageOne)
def dim_4(self):
self.dim = 4
self.controller.show_frame(PageOne)
def dim_5(self):
self.dim = 5
self.controller.show_frame(PageOne)
def dim_8(self):
self.dim = 8
self.controller.show_frame(PageOne)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.matrix = None
self.score = None
self.cells = []
for i in range(self.controller.dim):
row = []
for j in range(self.controller.dim):
cell_frame = tk.Frame(self, bg="light grey",
width=500 / self.controller.dim, height=500 / self.controller.dim)
cell_frame.grid(row=i+10, column=j, padx=10 / self.controller.dim, pady=10 / self.controller.dim)
cell_number = tk.Label(self, bg="light grey")
cell_number.grid(row=i+10, column=j)
cell_data = {"frame": cell_frame, "number": cell_number}
row.append(cell_data)
self.cells.append(row)
score_frame = tk.Frame(controller.main_grid)
score_frame.place(relx=0.5, y=50, anchor="center")
tk.Label(score_frame, text="Score", font="Helvetica 18 bold").grid(row=0)
self.score_label = tk.Label(score_frame, text="0", font="Helvetica 24 bold")
self.score_label.grid(row=1)
self.start_game()
def start_game(self):
self.matrix = [[0] * self.controller.dim for _ in range(self.controller.dim)]
row = random.randint(0, self.controller.dim - 1)
col = random.randint(0, self.controller.dim - 1)
self.matrix[row][col] = 2
self.cells[row][col]["frame"].configure(bg="white")
self.cells[row][col]["number"].configure(bg="white", fg="black", font="Helvetica 24 bold", text="2")
while self.matrix[row][col] != 0:
row = random.randint(0, self.controller.dim - 1)
col = random.randint(0, self.controller.dim - 1)
self.matrix[row][col] = 2
self.cells[row][col]["frame"].configure(bg="white")
self.cells[row][col]["number"].configure(bg="white", fg="black", font="Helvetica 24 bold", text="2")
self.score = 0
# move all numbers on the left side
def stack(self):
new_matrix = [[0] * self.controller.dim for _ in range(self.controller.dim)]
for i in range(self.controller.dim):
fill_pos = 0
for j in range(self.controller.dim):
if self.matrix[i][j] != 0:
new_matrix[i][fill_pos] = self.matrix[i][j]
fill_pos += 1
self.matrix = new_matrix
# sum numbers horizontally and combine equal numbers
def combine(self):
for i in range(self.controller.dim):
for j in range(self.controller.dim - 1):
if self.matrix[i][j] != 0 and self.matrix[i][j] == self.matrix[i][j + 1]:
self.matrix[i][j] *= 2
self.matrix[i][j + 1] = 0
self.score += self.matrix[i][j]
# this function reverses the order of each row
def reverse(self):
new_matrix = []
for i in range(self.controller.dim):
new_matrix.append([])
for j in range(self.controller.dim):
new_matrix[i].append(self.matrix[i][self.controller.dim - 1 - j])
self.matrix = new_matrix
def transpose(self):
new_matrix = [[0] * self.controller.dim for _ in range(self.controller.dim)]
for i in range(self.controller.dim):
for j in range(self.controller.dim):
new_matrix[i][j] = self.matrix[j][i]
self.matrix = new_matrix
def add_number(self):
if any(0 in row for row in self.matrix):
row = random.randint(0, self.controller.dim - 1)
col = random.randint(0, self.controller.dim - 1)
while self.matrix[row][col] != 0:
row = random.randint(0, self.controller.dim - 1)
col = random.randint(0, self.controller.dim - 1)
self.matrix[row][col] = random.choice([2, 2, 2, 2, 4])
def update_GUI(self):
for i in range(self.controller.dim):
for j in range(self.controller.dim):
cell_value = self.matrix[i][j]
if cell_value == 0:
self.cells[i][j]["frame"].configure(bg="light grey")
self.cells[i][j]["number"].configure(bg="light grey", text="")
else:
self.cells[i][j]["frame"].configure(bg=NUMBER_COLOR[cell_value])
self.cells[i][j]["number"].configure(bg=NUMBER_COLOR[cell_value], fg="black",
font="Helvetica 24 bold", text=str(cell_value))
self.score_label.configure(text=self.score)
self.update_idletasks()
self.game_over()
def left(self, event):
self.stack()
self.combine()
self.stack()
self.add_number()
self.update_GUI()
self.game_over()
def right(self, event=None):
self.reverse()
self.stack()
self.combine()
self.stack()
self.reverse()
self.add_number()
self.update_GUI()
self.game_over()
def up(self, event=None):
self.transpose()
self.stack()
self.combine()
self.stack()
self.transpose()
self.add_number()
self.update_GUI()
self.game_over()
def down(self, event=None):
self.transpose()
self.reverse()
self.stack()
self.combine()
self.stack()
self.reverse()
self.transpose()
self.add_number()
self.update_GUI()
def horiz_moves(self):
for i in range(self.controller.dim):
for j in range(self.controller.dim - 1):
if self.matrix[i][j] == self.matrix[i][j + 1]:
return True
return False
def vert_moves(self):
for i in range(self.controller.dim - 1):
for j in range(self.controller.dim):
if self.matrix[i][j] == self.matrix[i + 1][j]:
return True
return False
def number(self):
if self.controller.dim == 3:
return 8
elif self.controller.dim == 4:
return 2048
elif self.controller.dim == 5:
return 8192
else:
return 16384
def restart(self):
self.bind("<Return>", os.execl(sys.executable, sys.executable, *sys.argv))
def game_over(self):
tk.Frame(self).place(relx=0.5, rely=0.5, anchor="center")
if not any(0 in row for row in self.matrix) and not self.horiz_moves() and not self.vert_moves():
top = tk.Toplevel()
top.geometry("300x100")
top.title("toplevel")
l2 = tk.Label(top, text="Game Over\n What do you want do?",
fg="white", font="Helvetica 12 bold")
l2.pack()
tk.Button(top, text="Restart", bg="green",
fg="white", font="Helvetica 10 bold",
command=self.restart).pack(side='left')
tk.Button(top, text="Quit", bg="red",
fg='white', font="Helvetica 10 bold", command=self.bind("<Return>", quit)).pack(side="right")
elif any(self.number() in row for row in self.matrix):
top = tk.Toplevel()
top.geometry("180x100")
top.title("toplevel")
l2 = tk.Label(top, text="You Win!\n What do you want do?", font="Helvetica 12 bold")
l2.pack()
tk.Button(top, text="Restart", bg="green",
fg="white", font="Helvetica 10 bold",
command=self.restart).pack(side='left')
tk.Button(top, text="Quit", bg="red",
fg='white', font="Helvetica 10 bold", command=self.bind("<Return>", quit)).pack(side="right")
def savegame(self):
f = open("savedata", "w")
line1 = " ".join(
[str(self.matrix[floor(x / self.controller.dim)][x % self.controller.dim])
for x in range(0, self.controller.dim ** 2)])
f.write(line1 + "\n")
f.write(str(self.controller.dim) + "\n")
f.write(str(self.score))
f.close()
def loadgame(self):
# self.score
# self.dim
# self.matrix
f = open("savedata", "r")
mat = (f.readline()).split(' ', self.controller.dim ** 2)
self.controller.dim = int(f.readline())
self.score = int(f.readline())
for i in range(0, self.controller.dim ** 2):
self.matrix[floor(i / self.controller.dim)][i % self.controller.dim] = int(mat[i])
f.close()
NUMBER_COLOR = {
2: "#fcefe6",
4: "#f2e8cb",
8: "#f5b682",
16: "#f29446",
32: "#ff775c",
64: "#e64c2e",
128: "#ede291",
256: "#fce130",
512: "#ffdb4a",
1024: "#f0b922",
2048: "#fad74d",
4096: "brown",
8192: "silver",
16384: "gold"
}
def main():
Game()
if __name__ == "__main__":
main()

Replace the code with the following:
self.bind("<Left>", self.frames[PageOne].left)
self.bind("<Right>", self.frames[PageOne].right)
self.bind("<Up>", self.frames[PageOne].up)
self.bind("<Down>", self.frames[PageOne].down)
The reason for your odd behavior is that you try to reach instances variables and methods but on the level of a class. It's not easy to explain in a few words, but you should research the difference between class an regular methods, the purpose of self and of course the documentation for classes and instances
Update
In order to make your dimensions work you need to create your matrix after you defined the dimensions, not when you initialize your Frame. The shortest way to achive this, is to create a function that is called when your dimension is defined.
In your PageOne you would do something like:
...
self.cells = []
def create_matrix(self):
for i in range(self.controller.dim):
...
score_frame = tk.Frame(self.controller.main_grid) #add self.
...
call this function when the user has chosen by (e.g):
def dim_3(self):
self.controller.dim = 3 #use self.controller dim
self.controller.frames[PageOne].create_matrix() #call create_matrix
self.controller.show_frame(PageOne)
and while you use the variable in your controller the following is not effective:
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
#self.dim = controller.dim
#is not a link to your var self.dim stores whats in controller.dim
Update2
in order to make your quit and restart work and with little improvements I have changed your code below. The code is left as an exercise since I still try to figure out the rules of the game. Happy codeing!
def restart(self):
for widget in self.winfo_children():
widget.destroy()
self.cells = []
self.controller.show_frame(StartPage)
def game_over(self):
tk.Frame(self).place(relx=0.5, rely=0.5, anchor="center")
if not any(0 in row for row in self.matrix) and not self.horiz_moves() and not self.vert_moves():
geo_string = "300x100"
title = "Game Over!"
text = "Game Over\n What do you want do?"
self.message(geo_string,title,text)
elif any(self.number() in row for row in self.matrix):
geo_string = "180x100"
title = "Congratulation!"
text = "You Win!\n What do you want do?"
self.message(geo_string,title,text)
def message(self, geo_string,title,text):
top = tk.Toplevel()
top.geometry(geo_string)
top.title(title)
l2 = tk.Label(top, text=text, font="Helvetica 12 bold")
l2.pack()
rbutton = tk.Button(top, text="Restart", bg="green",
fg="white", font="Helvetica 10 bold",
command=self.restart)
rbutton.bind('<ButtonRelease-1>',lambda e: self.controller.after(20,top.destroy))
rbutton.pack(side='left')
qbutton = tk.Button(top, text="Quit", bg="red",
fg='white', font="Helvetica 10 bold",
command=self.controller.destroy)
qbutton.pack(side="right")

Related

my code was working fine until i changed something and now it wont run, whats wrong?

something was wrong with my code and i tried to fix it, now it doesn't run at all, no window pops up, when i stop the code, it says Process finished with exit code -1. i think i changed something from line 24, but not sure what happened. please tell me everything that's wrong with the code, and i believe theres a few that i cant find. thanks
from tkinter import *
import random
p = 0
x = random.randint(5, 12)
y = random.randint(5, 12)
class Starting:
def __init__(self, master):
self.master = master
self.frame = Frame(master, padx=200, pady=200)
self.frame.grid()
self.title = Label(self.frame, text="Multi-level Maths Quiz",
font=("Helvetica", "20", "bold"))
self.title.grid(row=0, padx=30, pady=30)
self.usern = Label(self.frame,text="Please enter a username", font=("16"))
self.usern.grid(row=1, padx=20, pady=20)
self.userentry = Entry(self.frame, width=50)
self.userentry.grid(row=2)
self.usercont = Button(self.frame, text="Continue", command=self.clear1)
self.usercont.grid(row=3)
def clear1(self):
self.frame.destroy()
ins1 = Questions(self.master)
class Questions:
while p < 5:
def __init__ (self, master):
self.user_choice = StringVar()
self.user_choice.set("")
self.frame = Frame(master, padx=200, pady=200)
self.frame.grid()
self.q = Label(self.frame, text="What is {} + {} ?".format(x, y))
self.q.grid(row=0)
self.ans = Entry(self.frame, width=50, textvariable=self.user_choice)
self.ans.grid(row=1)
self.answer = x+y
self.sub = Button(self.frame, text="submit", command=self.correct)
self.sub.grid(row=3)
def correct(self):
if int(self.user_choice.get()) == self.answer:
cor = Label(text="Correct!")
cor.grid(row=3, pady=50)
global p
p += 1
else:
inc = Label(text="incorrect")
inc.grid(row=3)
if __name__ == "__main__":
root = Tk()
root.title = ("Maths Quiz")
instance = Starting(root)
root.mainloop()
The line
while p < 5:
seems strange to me being in a class definition before the initialisation. This means if your p is >= 5 the class will never actually be defined as anything. This does not seem intended. If you comment it out and re-indent your def __init__() and def correct(self): functions the code seems to run again

navigating screens is not working after calling class within class in tkinter

I want to navigate to the new screen after I click upon a button,this is working as a whole program, I mean if I write all the classes in a single file it works,but I want to organize the code with files so I created a new class and calling that class in the class of main file. But it outputs the blank screen.
code of file Menu
from Page import MenuPage
class SampleApp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.container = Frame(self)
self.container.pack()
self.frames = {}
for F in (StartPage, PageOne):
frame = F(self.container, self)
self.frames[F] = frame
frame.configure(width=2085, height=1080)
frame.config(bg='#020A2E')
frame.grid(row=0, column=0)
self.show_frame(StartPage)
def show_frame(self, controller):
frame = self.frames[controller]
frame.tkraise()
class StartPage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller=controller
canvas = Canvas(self,width=2085, height=1080, bg='#020A2E')
canvas.pack()
self.img = Image.open("images/b100.png")
self.my_img = ImageTk.PhotoImage(self.img)
canvas.create_image(200, 310, image=self.my_img, tags='close_tag')
self.imgg = Image.open("images/c100.png")
self.myimg = ImageTk.PhotoImage(self.imgg)
canvas.create_image(470, 310, image=self.myimg)
self.oimage = Image.open("images/o100.png")
self.omg = ImageTk.PhotoImage(self.oimage)
canvas.create_image(820, 310, image=self.omg)
self.timg = Image.open("images/t100.png")
self.tmg = ImageTk.PhotoImage(self.timg)
canvas.create_image(1150, 310, image=self.tmg)
canvas.create_text(665, 540, text="connect to headset", anchor=S, font='Arial 8 ', fill='white')
self.url = "wss://localhost:6868"
self.user = {
"license": "e2c901aa-0032-483e-976b-8d90957099ad",
"client_id": "uNU5UMKd9eFLYp8JtHr6ZXXaLHg1p6rf1BReVn4N",
"client_secret": "9wcDtQn2Wubjg7zzlO2tnkx8Hzk1GkLpqZsqgOiuaWsaI0VRkxcxeQ9ZOPrHrNvJ1tlgOAV1XEZ6ooxJ06sRwobXDApRsol08w9YsJWU0fVAieWYp6kHexOlM9OWqXWk",
"debit": 100
# "number_row_data" : 10
}
connect = Button(self,width=15, height=1, bd=0, bg='#2C3547', text="CONNECT", relief=RAISED,
font='Arial 10 bold ', fg='white', command=self.connection).place(x=600, y=500)
self.next = Image.open("images/next.png")
self.img_nxt = ImageTk.PhotoImage(self.next)
Button(self,width=35, height=30, bg='#020A2E', image=self.img_nxt, bd=0, command=lambda: controller.show_frame(PageOne)).place(x=1320, y=10)
def connection(self):
c = Cortex(self.url, self.user)
headset_id = c.query_headset()
c.connect_headset()
c.request_access()
messagebox.showinfo("BCOT", "headset connected")
auth = c.authorize()
c.create_session(auth, headset_id)
class PageOne(Frame):
def __init__(self,parent,controller):
Frame.__init__(self,parent)
self.controller=controller
m = MenuPage(parent,controller)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
from the class PageOne I want to call another class which is present in different file called 'Page.py'-it has all the widgets and the items.so now I want to display all the code of Page.py in the
PageOne class
here is my Page.py file:
class MenuPage(Frame):
def __init__(self, parent, controller, **kw):
Frame.__init__(self,parent)
self.image1 = PhotoImage(file=r'images/iot.png')
self.image2 = PhotoImage(file=r'images/facialExp.png')
self.image3 = PhotoImage(file=r'images/cursor.png')
self.image4 = PhotoImage(file=r'images/mindR.png')
self.imgg = PhotoImage(file=r'images/arrow.png')
self.controller = controller
self.canvas = Canvas(self,width=2085, height=1080, bg='#020A2E')
self.canvas.pack()
label = Label(self,text="FEATURES", bg='#020A2E', fg='white', font='Arial 50 bold').place(x=80, y=20)
from Menu import StartPage
arrow = Button(self,width=40, height=30, bg='#020A2E', image=self.imgg, bd=0,
command=lambda:controller.show_frame(StartPage)).place(x=10, y=10)
button1 =Button(self,width=200, height=215, bg="#3A3535", bd=0, image=self.image1).place(x=380, y=150)
self.canvas.create_rectangle(75, 150, 380, 365, fill='#615A5A')
self.canvas.create_text(220, 160, text="TURN ON THE LIGHTS", anchor=N, font='Arial 14 bold', fill='white')
# label1= Label(root,text="TURN ON THE LIGHTS",fg='yellow',font='Arial 10 bold').place(x=100,y=160)
# label11 = Label(root,text="just move your head towards left and blink\nyour eye twice to open this feature or tap\nthe icon if you are using the cursor",fg='yellow',font='Arial 10 bold').place(x=90,y=200)
# canvas.create_rectangle(50,130,610,390,fill='#FFFFFF',stipple="gray12") #hover on tile1
button2 = Button(self,width=200, height=215, bg="#3A3535", bd=0, image=self.image2).place(x=1100, y=150)
self.canvas.create_rectangle(795, 150, 1101, 368, fill='#615A5A')
#label2 = tk.Label(text="TURN ON THE LIGHTS", fg='yellow', bg='#615A5A', font='Arial 10 bold').place(x=900,y=160)
# canvas.create_rectangle(770, 130,1325,390, fill='#FFFFFF')
button3 = Button(self,width=200, height=215, bg="#3A3535", bd=0, image=self.image3).place(x=380, y=450)
self.canvas.create_rectangle(75, 450, 380, 667, fill='#615A5A')
# canvas.create_rectangle(50,430,607,690,fill='#FFFFFF')
button4 = Button(self,width=200, height=215, bg="#3A3535", bd=0, image=self.image4).place(x=1100, y=450)
self.canvas.create_rectangle(795, 450, 1100, 669, fill='#615A5A')
# canvas.create_rectangle(770,430,1325,688,fill='#FFFFFF')
self.img = Image.open("images/sky.png")
self.my_img = ImageTk.PhotoImage(self.img)
self.my_rectangle = self.canvas.create_image(330, 255, image=self.my_img, tags='close_tag')
# my_rectangle=canvas.create_rectangle(50,130,610,390,fill="#FFFFFF", stipple="gray12")
parent.master.bind("<Left>", self.left)
parent.master.bind("<Right>", self.right)
parent.master.bind("<Up>", self.up)
parent.master.bind("<Down>", self.down)
def left(self, event):
x = -720
y = 0
# xx=event.xx
# yy=event.yy
pos = self.canvas.coords('close_tag')
if pos == [1050.0, 255.0] or pos == [1050.0, 555.0]:
print('left', pos)
self.canvas.move(self.my_rectangle, x, y)
def right(self, event):
x = 720
y = 0
pos = self.canvas.coords('close_tag')
if pos == [330.0, 255.0] or pos == [330.0, 555.0]:
print('right', pos)
self.canvas.move(self.my_rectangle, x, y)
def up(self, event):
x = 0
y = -300
pos = self.canvas.coords('close_tag')
if pos == [330.0, 555.0] or pos == [1050.0, 555.0]:
print('up', pos)
self.canvas.move(self.my_rectangle, x, y)
def down(self, event):
x = 0
y = 300
pos = self.canvas.coords('close_tag')
if pos == [330.0, 255.0] or pos == [1050.0, 255.0]:
print('down', pos)
self.canvas.move(self.my_rectangle, x, y)
I tried but i think the there is a conflict in the init function of PageOne and Page.py file's class so I am getting blank screen.
I need your help guys

How can I sum up the values of two functions? (2.0)

As I promised yesterday, here comes the real code.
I am about to code a program, for defining the reverberation time in a room. Explaining the whole project, takes too much time. I tried the approach which was suggested, but I do something wrong...
In PageOne, there are all the degrees of absorption of the materials in different sound frequencies and in PageTwo, the user has to enter the area in square meters and choose the material. As soon as the OK-button is pressed the functions getBottomChoice and getWallChoice multiply the values of the materials in PageOne with the userinput, to get the absorption area. But unfortunately it doesn't work. And how can I print out the new values(absorption area) of the chosen materials, just for checkin out? And last but not least, how can I sum up the abs.areas of the chosen materials and print it out, listed by the frequencies ? Thanks in advance!
import tkinter as tk
from tkinter import ttk
from tkinter import *
import math
LARGE_FONT = ("Verdana", 12)
class ReverberationTime(tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "reverberation time")
tk.Tk.iconbitmap(self,"C:/Users/PC/Desktop/Icons/speaker.ico")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo, PageThree):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self,cont):
frame = self.frames[cont]
frame.tkraise()
class Pages:
p = 0
z = 1
abs_flä = 1
def __init__(self):
self.parkett_125 = 0.04
self.parkett_250 = 0.04
self.parkett_500 = 0.05
self.parkett_1000 = 0.06
self.parkett_2000 = 0.06
self.parkett_4000 = 0.06
self.linoleum_125 = 0.02
self.linoleum_250 = 0.02
self.linoleum_500 = 0.03
self.linoleum_1000 = 0.03
self.linoleum_2000 = 0.04
self.linoleum_4000 = 0.04
self.pvc_125 = 0.02
self.pvc_250 = 0.02
self.pvc_500 = 0.01
self.pvc_1000 = 0.03
self.pvc_2000 = 0.05
self.pvc_4000 = 0.05
self.tapete_125 = 0.02
self.tapete_250 = 0.03
self.tapete_500 = 0.04
self.tapete_1000 = 0.05
self.tapete_2000 = 0.07
self.tapete_4000 = 0.08
self.glattputz_125 = 0.02
self.glattputz_250 = 0.02
self.glattputz_500 = 0.03
self.glattputz_1000 = 0.03
self.glattputz_2000 = 0.04
self.glattputz_4000 = 0.06
self.mauerziegelwand_125 = 0.02
self.mauerziegelwand_250 = 0.02
self.mauerziegelwand_500 = 0.03
self.mauerziegelwand_1000 = 0.04
self.mauerziegelwand_2000 = 0.05
self.mauerziegelwand_4000 = 0.06
def bottoms(self,parkett_125,parkett_250,parkett_500,parkett_1000,
parkett_2000,parkett_4000,linoleum_125,linoleum_250,linoleum_500,
linoleum_1000,linoleum_2000,linoleum_4000,pvc_125,
pvc_250,pvc_500,pvc_1000,pvc_2000,pvc_4000):
self.parkett_125 = parkett_125
self.parkett_250 = parkett_250
self.parkett_500 = parkett_500
self.parkett_1000 = parkett_1000
self.parkett_2000 = parkett_2000
self.parkett_4000 = parkett_4000
self.linoleum_125 = linoleum_125
self.linoleum_250 = linoleum_250
self.linoleum_500 = linoleum_500
self.linoleum_1000 = linoleum_1000
self.linoleum_2000 = linoleum_2000
self.linoleum_4000 = linoleum_4000
self.pvc_125 = pvc_125
self.pvc_250 = pvc_250
self.pvc_500 = pvc_500
self.pvc_1000 = pvc_1000
self.pvc_2000 = pvc_2000
self.pvc_4000 = pvc_4000
def walls(self,tapete_125,tapete_250,tapete_500,tapete_1000,tapete_2000,tapete_4000,
glattputz_125,glattputz_250,glattputz_500,glattputz_1000,glattputz_2000,glattputz_4000,
mauerziegelwand_125,mauerziegelwand_250,mauerziegelwand_500,mauerziegelwand_1000,mauerziegelwand_2000,mauerziegelwand_4000):
self.tapete_125 = tapete_125
self.tapete_250 = tapete_250
self.tapete_500 = tapete_500
self.tapete_1000 = tapete_1000
self.tapete_2000 = tapete_2000
self.tapete_4000 = tapete_4000
self.glattputz_125 = glattputz_125
self.glattputz_250 = glattputz_250
self.glattputz_500 = glattputz_500
self.glattputz_1000 = glattputz_1000
self.glattputz_2000 = glattputz_2000
self.glattputz_4000 = glattputz_4000
self.mauerziegelwand_125 = mauerziegelwand_125
self.mauerziegelwand_250 = mauerziegelwand_250
self.mauerziegelwand_500 = mauerziegelwand_500
self.mauerziegelwand_1000 = mauerziegelwand_1000
self.mauerziegelwand_2000 = mauerziegelwand_2000
self.mauerziegelwand_4000 = mauerziegelwand_4000
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="reverberation time", font=LARGE_FONT)
label.pack(pady = 10, padx = 10)
button = ttk.Button(self, text="welcome!",
command=lambda: controller.show_frame(PageOne)).pack()
class PageOne(tk.Frame, Pages):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
NORMAL_FONT=("Arial",11)
title = tk.Label(self, text="Please enter the room dimensions.", font=LARGE_FONT)
title.pack(pady = 10, padx = 10)
frame = Frame(self)
frame.pack(pady=20)
self.lenght = StringVar()
self.width = StringVar()
self.height = StringVar()
self.v = StringVar()
dimensions = Frame(frame)
dimensions.pack(side='left', pady=5)
entryfields = Frame(frame)
entryfields.pack(side='right', pady=5)
lblLenght = Label(dimensions, text="lenght:", font=NORMAL_FONT)
lblLenght.pack(pady=3)
lblWidth = Label(dimensions, text="width:", font=NORMAL_FONT)
lblWidth.pack(pady=4)
lblHeight = Label(dimensions, text="height:", font=NORMAL_FONT)
lblHeight.pack(pady=4)
lblVolume = Label(dimensions, textvariable = self.v)
lblVolume.pack()
entLength = Entry(entryfields, textvariable = self.lenght)
entLength.pack(pady=6)
entWidth = Entry(entryfields, textvariable = self.width)
entWidth.pack(pady=6)
entHeight = Entry(entryfields, textvariable = self.height)
entHeight.pack(pady=6)
btncalculate = ttk.Button(self, text="calculate")
btncalculate.pack()
btncalculate.bind("<Button-1>", self.calculate)
btnPageTwo = ttk.Button(self, text="Page 2", command=lambda: controller.show_frame(PageTwo))
btnPageTwo.pack()
btnStartPage = ttk.Button(self, text="Start Page", command=lambda: controller.show_frame(StartPage))
btnStartPage.pack()
def calculate(self, carryout):
try:
l = float(self.lenght.get())
b = float(self.width.get())
h = float(self.height.get())
m = l*b*h
self.v.set("volume: % .2f m³" % m)
Pages.p = m
except ValueError:
tk.messagebox.showinfo('No valid input.','Please enter only numbers!',icon = 'warning')
class PageTwo(tk.Frame, Pages):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
NORMAL_FONT=("Arial",11)
title = tk.Label(self, text="Please select the bottom abilities.", font=LARGE_FONT)
title.pack(pady = 10, padx = 10)
self.bottomMaterial =StringVar()
self.bottom = StringVar()
self.wallMaterial =StringVar()
self.wall = StringVar()
frame = Frame(self)
frame.pack(pady=20)
dimensions = Frame(frame)
dimensions.pack(side='left', pady=5)
entBottom = Entry(dimensions, textvariable = self.bottom)
entBottom.grid(pady = 5)
self.cboBottomMaterial = ttk.Combobox(dimensions, textvariable = self.bottomMaterial, state = 'readonly',font = ('arial', 14, 'bold'), width = 19)
self.cboBottomMaterial ['value'] = ('Parkett', 'Linoleum', 'PVC')
self.cboBottomMaterial.current(0)
self.cboBottomMaterial.grid()
btnBottomChoice = ttk.Button(dimensions, text = "OK", command = self.getBottomChoice)
btnBottomChoice.grid()
entWall = Entry(dimensions, textvariable = self.wall)
entWall.grid(pady = 5)
self.cboWallMaterial = ttk.Combobox(dimensions, textvariable = self.wallMaterial, state = 'readonly',font = ('arial', 14, 'bold'), width = 19)
self.cboWallMaterial ['value'] = ('Tapete', 'Glattputz', 'Mauerziegelwand')
self.cboWallMaterial.current(0)
self.cboWallMaterial.grid()
btnWallChoice = ttk.Button(dimensions, text = "OK", command = self.getWallChoice)
btnWallChoice.grid()
btnsumAbsorptionArea = ttk.Button(self, text="sum")
btnsumAbsorptionArea.pack()
btnsumAbsorptionArea.bind("<Button-1>", self.sumAbsorptionArea)
btnPageTwo = ttk.Button(self, text="Page 1", command=lambda: controller.show_frame(PageOne))
btnPageTwo.pack()
btnStartPage = ttk.Button(self, text="Start Page", command=lambda: controller.show_frame(StartPage))
btnStartPage.pack()
btnStartPage = ttk.Button(self, text="Page 3", command=lambda: controller.show_frame(PageThree))
btnStartPage.pack()
def getBottomChoice(self):
if self.cboBottomMaterial.get() == "Parkett":
self.bottoms(
self.parkett_125 * float(self.bottom.get()),
self.parkett_250 * float(self.bottom.get()),
self.parkett_500 * float(self.bottom.get()),
self.parkett_1000 * float(self.bottom.get()),
self.parkett_2000 * float(self.bottom.get()),
self.parkett_4000 * float(self.bottom.get())
)
elif self.cboBottomMaterial.get() == "Linoleum":
self.bottoms(
self.linoleum_125 * float(self.bottom.get()),
self.linoleum_250 * float(self.bottom.get()),
self.linoleum_500 * float(self.bottom.get()),
self.linoleum_1000 * float(self.bottom.get()),
self.linoleum_2000 * float(self.bottom.get()),
self.linoleum_4000 * float(self.bottom.get())
)
elif self.cboBottomMaterial.get() == "PVC":
self.bottoms(
self.pvc_250 * float(self.bottom.get()),
self.pvc_500 * float(self.bottom.get()),
self.pvc_1000 * float(self.bottom.get()),
self.pvc_2000 * float(self.bottom.get()),
self.pvc_4000 * float(self.bottom.get())
)
elif self.cboBottomMaterial.get() == "":
messagebox.showinfo('No valid input.','Please select.',icon = 'warning')
def getWallChoice(self):
if self.cboWallMaterial.get() == "Tapete":
self.walls(
self.tapete_125 * float(self.wall.get()),
self.tapete_250 * float(self.wall.get()),
self.tapete_500 * float(self.wall.get()),
self.tapete_1000 * float(self.wall.get()),
self.tapete_2000 * float(self.wall.get()),
self.tapete_4000 * float(self.wall.get())
)
elif self.cboWallMaterial.get() == "Glattputz":
self.walls(
self.glattputz_125 * float(self.wall.get()),
self.glattputz_250 * float(self.wall.get()),
self.glattputz_500 * float(self.wall.get()),
self.glattputz_1000 * float(self.wall.get()),
self.glattputz_2000 * float(self.wall.get()),
self.glattputz_4000 * float(self.wall.get())
)
elif self.cboWallMaterial.get() == "Mauerziegelwand":
self.walls(
self.mauerziegelwand_250 * float(self.wall.get()),
self.mauerziegelwand_500 * float(self.wall.get()),
self.mauerziegelwand_1000 * float(self.wall.get()),
self.mauerziegelwand_2000 * float(self.wall.get()),
self.mauerziegelwand_4000 * float(self.wall.get())
)
elif self.cboWallMaterial.get() == "":
messagebox.showinfo('No valid input.','Please select.',icon = 'warning')
def sumAbsorptionArea(self,sum):
sum = self.getBottomChoice + self.getWallChoice
print (sum)
class PageThree(tk.Frame, Pages):
def passvariable(self, var):
self.s.set("volume: % .2f m³" % Pages.p)
def absorptionsrate(self, var):
self.abs_rate.set("volume: % .2f m³" % Pages.abs_flä)
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
frame = Frame(self)
frame.pack(pady=20)
result_var = StringVar()
selected_var = StringVar()
self.s = StringVar()
items_for_listbox = ["Musik","Sprache","Vortrag","Spr.+Vor.","Sport"]
self.abs_rate = StringVar()
def select(event):
a = mylistbox.get(ANCHOR)
Pages.z = curselection(a)
selected_var.set(Pages.z)
def curselection(a):
if a=="Musik":
T_soll_A1 = 0.45*math.log10(Pages.p)+0.07
return (T_soll_A1)
elif a=="Sprache":
T_soll_A2 = 0.37*math.log10(Pages.p)-0.14
return (T_soll_A2)
elif a=="Vortrag":
T_soll_A3 = 0.32*math.log10(Pages.p)-0.17
return (T_soll_A3)
elif a=="Spr.+Vor.":
T_soll_A4 = 0.26*math.log10(Pages.p)-0.14
return (T_soll_A4)
elif a=="Sport":
T_soll_A5 = 0.75*math.log10(Pages.p)-1
return (T_soll_A5)
def calc():
if mylistbox.get(ACTIVE):
Abs_Fl_ges = 0.163 * Pages.p / Pages.z
Absorber = Abs_Fl_ges - Pages.abs_flä
result_var.set(Absorber)
elif Pages.z == 0:
messagebox.showinfo("No selection")
self.dimension = Frame(frame)
self.dimension.pack(side='left', pady=5)
lblPageTwo = tk.Label(self, text="Page 2", font=LARGE_FONT)
lblPageTwo.pack(pady = 10, padx = 10)
lblAbs_rate = tk.Label(self.dimension, textvariable = self.abs_rate)
lblAbs_rate.pack()
pasvar = tk.Label(self.dimension, textvariable = self.s)
pasvar.pack()
lblselection = tk.Label(self.dimension, textvariable=selected_var)
lblselection.pack(expand=YES)
selected_var.set("No selection")
lblresult = Label(self.dimension, textvariable=result_var)
lblresult.pack(expand=YES)
result_var.set("No result")
listbox_frame = Frame(self.dimension)
listbox_frame.pack(expand=YES)
mylistbox = Listbox(listbox_frame, height=5, width=10, font=('times',18))
mylistbox.bind('<<ListboxSelect>>', select)
mylistbox.grid(row=0, column=0)
mylistbox.insert(END, *items_for_listbox)
scroll = Scrollbar(listbox_frame, orient=VERTICAL) # the alignment of the scrollbar
mylistbox["yscrollcommand"] = scroll.set # link the list with the scroll
scroll["command"] = mylistbox.yview # link the scroll with the scroll
scroll.grid(row=0, column=1, sticky=N+S) #sticky=N+S+E)
btnAbsorber=Button(self.dimension, text="Fläche der Absorber", command=calc)
btnAbsorber.pack(expand=YES)
btnStartPage = ttk.Button(self, text="Start Page", command=lambda: controller.show_frame(StartPage))
btnStartPage.pack()
btnPageOne = ttk.Button(self, text="Page 1", command=lambda: controller.show_frame(PageOne))
btnPageOne.pack()
btnPageTwo = ttk.Button(self, text="Page 2", command=lambda: controller.show_frame(PageTwo))
btnPageTwo.pack()
btnPassVariable = ttk.Button(self, text="pasvariable")
btnPassVariable.pack()
btnPassVariable.bind("<Button-1>", self.passvariable)
btnAbs_rate = ttk.Button(self, text="pass absorption rate")
btnAbs_rate.pack()
btnAbs_rate.bind("<Button-1>", self.absorptionsrate)
app = ReverberationTime()
app.mainloop() ```
Ok so going off of our conversation in the comments and some assumptions I had to make about how things connect I have refactored your code.
Let me know if anything is not working as exspected.
4 spaces for indention is the standard. It helps with readability and if you follow the standard you can avoid issues like mismatching indention.
Make sure you have all your imports in your examples as this is an important troubleshooting step and lets us know what libraries we may need to test your examples.
I have refactored your code to follow the PEP8 standard. You had a mix of formatting going on and nothing was consistent.
It can be tricky to inherit from multiple classes so instead inherit from Frame and then create a class attribute that is an instance of Pages
Your functions that create new values from the attributes in Pages doesn't work like you are expecting. Instead you will want to sum everything then return that summed value.
Your math in your sumAbsorptionArea method cannot work as you are using a reference to methods instead of executing those methods.
You use a mix of command and bind on your buttons for some reason and because of this you have to have an event variable in some of your functions/methods. Instead just use command.
Personally you use a lot of lines up for defining attributes. I would work out a way to shorten this. Preferable a list of values or a dictionary would work well here. You can work that one out on your own though. :D
Refactored code:
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import math
LARGE_FONT = ("Verdana", 12)
class ReverberationTime(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "reverberation time")
# tk.Tk.iconbitmap(self, "C:/Users/PC/Desktop/Icons/speaker.ico")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo, PageThree):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class Pages:
p, z, abs_flä = 0, 1, 1
def __init__(self):
self.parkett_125 = 0.04
self.parkett_250 = 0.04
self.parkett_500 = 0.05
self.parkett_1000 = 0.06
self.parkett_2000 = 0.06
self.parkett_4000 = 0.06
self.linoleum_125 = 0.02
self.linoleum_250 = 0.02
self.linoleum_500 = 0.03
self.linoleum_1000 = 0.03
self.linoleum_2000 = 0.04
self.linoleum_4000 = 0.04
self.pvc_125 = 0.02
self.pvc_250 = 0.02
self.pvc_500 = 0.01
self.pvc_1000 = 0.03
self.pvc_2000 = 0.05
self.pvc_4000 = 0.05
self.tapete_125 = 0.02
self.tapete_250 = 0.03
self.tapete_500 = 0.04
self.tapete_1000 = 0.05
self.tapete_2000 = 0.07
self.tapete_4000 = 0.08
self.glattputz_125 = 0.02
self.glattputz_250 = 0.02
self.glattputz_500 = 0.03
self.glattputz_1000 = 0.03
self.glattputz_2000 = 0.04
self.glattputz_4000 = 0.06
self.mauerziegelwand_125 = 0.02
self.mauerziegelwand_250 = 0.02
self.mauerziegelwand_500 = 0.03
self.mauerziegelwand_1000 = 0.04
self.mauerziegelwand_2000 = 0.05
self.mauerziegelwand_4000 = 0.06
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="reverberation time", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button = ttk.Button(self, text="welcome!",
command=lambda: controller.show_frame(PageOne)).pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
super(PageOne).__init__()
self.Pages = Pages()
normal_font = ("Arial", 11)
tk.Label(self, text="Please enter the room dimensions.", font=LARGE_FONT).pack(pady=10, padx=10)
frame = tk.Frame(self)
frame.pack(pady=20)
self.length = tk.StringVar()
self.width = tk.StringVar()
self.height = tk.StringVar()
self.v = tk.StringVar()
dimensions = tk.Frame(frame)
dimensions.pack(side='left', pady=5)
entry_fields = tk.Frame(frame)
entry_fields.pack(side='right', pady=5)
tk.Label(dimensions, text="length:", font=normal_font).pack(pady=3)
tk.Label(dimensions, text="width:", font=normal_font).pack(pady=4)
tk.Label(dimensions, text="height:", font=normal_font).pack(pady=4)
tk.Label(dimensions, textvariable=self.v).pack()
tk.Entry(entry_fields, textvariable=self.length).pack(pady=6)
tk.Entry(entry_fields, textvariable=self.width).pack(pady=6)
tk.Entry(entry_fields, textvariable=self.height).pack(pady=6)
ttk.Button(self, text="calculate", command=self.calculate).pack()
ttk.Button(self, text="Page 2", command=lambda: controller.show_frame(PageTwo)).pack()
ttk.Button(self, text="Start Page", command=lambda: controller.show_frame(StartPage)).pack()
def calculate(self):
try:
l = float(self.length.get())
b = float(self.width.get())
h = float(self.height.get())
m = l*b*h
self.v.set("volume: % .2f m³" % m)
self.Pages.p = m
except ValueError:
tk.messagebox.showinfo('No valid input.', 'Please enter only numbers!', icon = 'warning')
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# normal_font = ("Arial", 11) # not used
self.Pages = Pages()
title = tk.Label(self, text="Please select the bottom abilities.", font=LARGE_FONT)
title.pack(pady=10, padx=10)
self.bottomMaterial = tk.StringVar()
self.bottom = tk.StringVar()
self.wallMaterial = tk.StringVar()
self.wall = tk.StringVar()
frame = tk.Frame(self)
frame.pack(pady=20)
dimensions = tk.Frame(frame)
dimensions.pack(side='left', pady=5)
tk.Entry(dimensions, textvariable=self.bottom).grid(pady=5)
self.cboBottomMaterial = ttk.Combobox(dimensions, textvariable=self.bottomMaterial,
state='readonly', font=('arial', 14, 'bold'), width=19)
self.cboBottomMaterial['value'] = ('Parkett', 'Linoleum', 'PVC')
self.cboBottomMaterial.current(0)
self.cboBottomMaterial.grid()
ttk.Button(dimensions, text="OK", command=self.get_bottom_choice).grid()
tk.Entry(dimensions, textvariable=self.wall).grid(pady=5)
self.cboWallMaterial = ttk.Combobox(dimensions, textvariable=self.wallMaterial,
state='readonly', font=('arial', 14, 'bold'), width=19)
self.cboWallMaterial['value'] = ('Tapete', 'Glattputz', 'Mauerziegelwand')
self.cboWallMaterial.current(0)
self.cboWallMaterial.grid()
ttk.Button(dimensions, text="OK", command=self.get_wall_choice).grid()
ttk.Button(self, text="sum", command=self.sum_absorption_area).pack()
ttk.Button(self, text="Page 1", command=lambda: controller.show_frame(PageOne)).pack()
ttk.Button(self, text="Start Page", command=lambda: controller.show_frame(StartPage)).pack()
ttk.Button(self, text="Page 3", command=lambda: controller.show_frame(PageThree)).pack()
def get_bottom_choice(self):
if self.cboBottomMaterial.get() == "Parkett":
parkett_125 = self.Pages.parkett_125 * float(self.bottom.get())
parkett_250 = self.Pages.parkett_250 * float(self.bottom.get())
parkett_500 = self.Pages.parkett_500 * float(self.bottom.get())
parkett_1000 = self.Pages.parkett_1000 * float(self.bottom.get())
parkett_2000 = self.Pages.parkett_2000 * float(self.bottom.get())
parkett_4000 = self.Pages.parkett_4000 * float(self.bottom.get())
return sum([parkett_125, parkett_250, parkett_500, parkett_1000, parkett_2000, parkett_4000])
elif self.cboBottomMaterial.get() == "Linoleum":
linoleum_125 = self.Pages.linoleum_125 * float(self.bottom.get()),
linoleum_250 = self.Pages.linoleum_250 * float(self.bottom.get())
linoleum_500 = self.Pages.linoleum_500 * float(self.bottom.get())
linoleum_1000 = self.Pages.linoleum_1000 * float(self.bottom.get())
linoleum_2000 = self.Pages.linoleum_2000 * float(self.bottom.get())
linoleum_4000 = self.Pages.linoleum_4000 * float(self.bottom.get())
return sum([linoleum_125, linoleum_250, linoleum_500, linoleum_1000, linoleum_2000, linoleum_4000])
elif self.cboBottomMaterial.get() == "PVC":
pvc_250 = self.Pages.pvc_250 * float(self.bottom.get()),
pvc_500 = self.Pages.pvc_500 * float(self.bottom.get())
pvc_1000 = self.Pages.pvc_1000 * float(self.bottom.get())
pvc_2000 = self.Pages.pvc_2000 * float(self.bottom.get())
pvc_4000 = self.Pages.pvc_4000 * float(self.bottom.get())
return sum([pvc_250, pvc_500, pvc_1000, pvc_2000, pvc_4000])
elif self.cboBottomMaterial.get() == "":
messagebox.showinfo('No valid input.', 'Please select.', icon='warning')
return 0
def get_wall_choice(self):
if self.cboWallMaterial.get() == "Tapete":
tapete_125 = self.Pages.tapete_125 * float(self.wall.get())
tapete_250 = self.Pages.tapete_250 * float(self.wall.get())
tapete_500 = self.Pages.tapete_500 * float(self.wall.get())
tapete_1000 = self.Pages.tapete_1000 * float(self.wall.get())
tapete_2000 = self.Pages.tapete_2000 * float(self.wall.get())
tapete_4000 = self.Pages.tapete_4000 * float(self.wall.get())
return sum([tapete_125, tapete_250, tapete_500, tapete_1000, tapete_2000, tapete_4000])
elif self.cboWallMaterial.get() == "Glattputz":
glattputz_125 = self.Pages.glattputz_125 * float(self.wall.get())
glattputz_250 = self.Pages.glattputz_250 * float(self.wall.get())
glattputz_500 = self.Pages.glattputz_500 * float(self.wall.get())
glattputz_1000 = self.Pages.glattputz_1000 * float(self.wall.get())
glattputz_2000 = self.Pages.glattputz_2000 * float(self.wall.get())
glattputz_4000 = self.Pages.glattputz_4000 * float(self.wall.get())
return sum([glattputz_125, glattputz_250, glattputz_500, glattputz_1000, glattputz_2000, glattputz_4000])
elif self.cboWallMaterial.get() == "Mauerziegelwand":
mauerziegelwand_250 = self.Pages.mauerziegelwand_250 * float(self.wall.get())
mauerziegelwand_500 = self.Pages.mauerziegelwand_500 * float(self.wall.get())
mauerziegelwand_1000 = self.Pages.mauerziegelwand_1000 * float(self.wall.get())
mauerziegelwand_2000 = self.Pages.mauerziegelwand_2000 * float(self.wall.get())
mauerziegelwand_4000 = self.Pages.mauerziegelwand_4000 * float(self.wall.get())
return sum([mauerziegelwand_250, mauerziegelwand_500, mauerziegelwand_1000,
mauerziegelwand_2000, mauerziegelwand_4000])
elif self.cboWallMaterial.get() == "":
messagebox.showinfo('No valid input.', 'Please select.', icon='warning')
return 0
def sum_absorption_area(self):
the_sum = self.get_bottom_choice() + self.get_wall_choice()
print(the_sum)
class PageThree(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.Pages = Pages()
self.s = tk.StringVar()
self.result_var = tk.StringVar()
self.selected_var = tk.StringVar()
self.selected_var.set("No selection")
self.result_var.set("No result")
self.abs_rate = tk.StringVar()
items_for_listbox = ["Musik", "Sprache", "Vortrag", "Spr.+Vor.", "Sport"]
frame = tk.Frame(self)
frame.pack(pady=20)
self.dimension = tk.Frame(frame)
self.dimension.pack(side='left', pady=5)
tk.Label(self, text="Page 2", font=LARGE_FONT).pack(pady=10, padx=10)
tk.Label(self.dimension, textvariable=self.abs_rate).pack()
tk.Label(self.dimension, textvariable=self.s).pack()
tk.Label(self.dimension, textvariable=self.selected_var).pack(expand='yes')
tk.Label(self.dimension, textvariable=self.result_var).pack(expand='yes')
listbox_frame = tk.Frame(self.dimension)
listbox_frame.pack(expand='yes')
self.mylistbox = tk.Listbox(listbox_frame, height=5, width=10, font=('times', 18))
self.mylistbox.bind('<<ListboxSelect>>', self.select)
self.mylistbox.grid(row=0, column=0)
self.mylistbox.insert('end', *items_for_listbox)
scroll = tk.Scrollbar(listbox_frame, orient='vertical') # the alignment of the scrollbar
self.mylistbox["yscrollcommand"] = scroll.set # link the list with the scroll
scroll["command"] = self.mylistbox.yview # link the scroll with the scroll
scroll.grid(row=0, column=1, sticky='ns') # sticky=N+S+E)
tk.Button(self.dimension, text="Fläche der Absorber", command=self.calc).pack(expand='yes')
ttk.Button(self, text="Start Page", command=lambda: controller.show_frame(StartPage)).pack()
ttk.Button(self, text="Page 1", command=lambda: controller.show_frame(PageOne)).pack()
ttk.Button(self, text="Page 2", command=lambda: controller.show_frame(PageTwo)).pack()
ttk.Button(self, text="pasvariable", command=self.pass_variable).pack()
ttk.Button(self, text="pass absorption rate", command=self.absorptions_rate).pack()
def curselection(self, a):
if a == "Musik":
return 0.45 * math.log10(self.Pages.p) + 0.07
elif a == "Sprache":
return 0.37 * math.log10(self.Pages.p) - 0.14
elif a == "Vortrag":
return 0.32 * math.log10(self.Pages.p) - 0.17
elif a == "Spr.+Vor.":
return 0.26 * math.log10(Pages.p) - 0.14
elif a == "Sport":
return 0.75 * math.log10(Pages.p) - 1
def calc(self):
if self.mylistbox.get('active'):
abs_fl_ges = 0.163 * Pages.p / Pages.z
absorber = abs_fl_ges - Pages.abs_flä
self.result_var.set(absorber)
elif Pages.z == 0:
messagebox.showinfo("No selection")
def select(self, _=None):
a = self.mylistbox.get('anchor')
self.Pages.z = self.curselection(a)
self.selected_var.set(self.Pages.z)
def pass_variable(self):
self.s.set("volume: % .2f m³" % self.Pages.p)
def absorptions_rate(self):
self.abs_rate.set("volume: % .2f m³" % self.Pages.abs_flä)
if __name__ == '__main__':
ReverberationTime().mainloop()

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.

self.gridrange=8 is showing as a tuple when I want it to be an integer

#!/usr/bin/env python
import tkinter as tk
from tkinter import ttk
import math
import random
#positions are stored in label and number format
LARGE_FONT= ("Verdana", 12)
positions = ['label'+str(i)+str(j) for i in range(8) for j in range(8)]
class Application(tk.Frame):
global positions
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid(sticky=tk.N+tk.S+tk.E+tk.W)
#The entry screen
#label = tk.Label(self, text="""Begin.""", font=LARGE_FONT)
#label.grid(row=0, column=0, pady=10)
#label = tk.Label(self, text="""Exit.""", font=LARGE_FONT)
#label.grid(row=0, column=1, pady=10)
#button1 = ttk.Button(self, text="Start Game", command=self.start)
#button2 = ttk.Button(self, text="Quit Game", command=quit)
#button1.grid(row=1, column=0, pady=10)
#button2.grid(row=1, column=1, pady=1)
#def start(self):
#self.createWidgets()
self.master = master
app = tk.Frame(self.master, bg="yellow")
app.grid_rowconfigure(0, weight=1)
app.grid_columnconfigure(1, weight=1)
app.grid_columnconfigure(0, weight=1)
#app.pack(fill="both", expand=True)
# instructions and fonts
self.instructions = "Find the hidden treasure!\n\nUse the arrow keys to select where to look, then press Enter to check. \
There is a 50/50 chance you will be told the distance from the treasure. Keep hunting until you find it. Good luck!"
# create instructions widget
self.info = tk.Text(app, padx=10, pady=10,width=15,bd=0, height=19, bg="yellow")
self.info.insert(1.0,self.instructions)
self.info.grid(row=0,column=0,sticky='N'+'E'+'S'+'W')
# create island widget
self.island = tk.Text(app, bg="cyan", padx=40, pady=40, width=15, height=9, bd=0)
self.island.insert(1.0, "ready")
self.island.grid(row=0,column=1, stick='N'+'E'+'S'+'W', rowspan=3)
# restart button
#self.restart_b = tk.Button(app, text="Restart", bg="red", command=self.begin)
#self.restart_b.grid(row=2, column=0, pady=20)
# score labels and fields
self.score_lbl = tk.Label(app, text="Guesses: 0", bg="yellow")
self.score_lbl.grid(row=1, column=0)
#keep track og gold
self.gold_lbl = tk.Label(app, text="Gold: 0", bg="yellow")
self.gold_lbl.grid(row=3, column=0)
#gold and bandit positions
self.gridrange = 8
self.numchest = 10
self.bandits = 3
self.winscore = 100
# set keydown handler
root.bind("<Key>", self.key_pressed)
# best score variable
self.best_score = 0
# begin game
#self.begin()
#print self.treasure_pos
self.mainMenu()
def mainMenu(self):
self.t = tk.Toplevel(self.master, backgroun='red')
self.t.wm_title("Main Menu")
self.l = tk.Label(self.t, text="Welcome to Treasure Hunt", background='red')
self.l.pack(side="top", fill="both", expand=True, padx=100, pady=100)
self.t.lift(self.master)
#self.t.geometry('640x480+0+0')
self.play = tk.Button(self.t, text="play", bg="purple", command=self.letsplay)
self.play.pack(side='left', expand=True)
self.ops = tk.Button(self.t, text="options", bg="yellow", command=self.ops)
self.ops.pack(side='left', expand=True)
def ops(self):
self.opwin = tk.Toplevel(self.master, backgroun='red')
self.opwin.wm_title("Option Menu")
self.opl = tk.Label(self.opwin, text="Welcome to Treasure Hunt", background='red')
self.opl.pack(side="top", fill="both", expand=True, padx=100, pady=100)
self.opwin.lift()
#self.opwin.geometry('640x480+0+0')
self.appp = tk.Button(self.opwin, text="Apply", bg="purple", command=self.letsplay)
self.appp.pack(side='left', expand=True)
self.gridops = tk.Listbox(self.opwin, selectmode='SINGLE')
self.gridops.pack()
for i in range(6, 14):
self.gridops.insert(tk.END, i)
self.gridrange = self.gridops.curselection()
def letsplay(self):
self.t.destroy()
#self.opwin.destroy()
#self.begin()
self.createWidgets()
root.lift()
def createWidgets(self):
#print (self.gridrange)
root.lift()
root.after_cancel(self.tick)
self.matrix = [["#" for col in range(self.gridrange)] for row in range(self.gridrange)]
self.current_pos = [0,0]
self.treasure_pos = []
self.bandit_pos = []
#times treasure has been found
self.treasures_won = []
self.last_treasure = []
self.gold_found = 0
for i in range(0, self.numchest):
self.gold_xy = self.get_pos()
self.treasure_pos.append(self.gold_xy)
for i in self.treasure_pos:
print (i)
print (len(self.treasure_pos))
for i in range (0, self.bandits):
self.bandit_xy = self.get_pos()
self.bandit_pos.append(self.bandit_xy)
for i in self.bandit_pos:
print (i)
print (len(self.bandit_pos))
#self.treasure_pos = [0,0]
#print self.treasure_pos
self.sett()
top=self.winfo_toplevel()
self.entry_frame = tk.Frame(self)
self.entry_frame.grid(row=0, column=0,rowspan=1,columnspan=8,sticky=tk.N+tk.E+tk.W)
self.pos_frame = tk.Frame(self)
self.pos_frame.grid(row=1, column=0,columnspan=8,sticky=tk.N+tk.S+tk.E+tk.W)
self.entry_frame.rowconfigure(0,weight=2)
screenx=self.pos_frame.winfo_width()
screeny=self.pos_frame.winfo_height()
for i in range(8):
top.rowconfigure(i,weight=1)
top.columnconfigure(i,weight=1)
self.pos_frame.columnconfigure(i,weight=1)
self.pos_frame.rowconfigure(i,weight=1)
self.entry_frame.columnconfigure(i,weight=1)
self.rowconfigure(i,weight=1)
self.columnconfigure(i,weight=1)
self.label_no_of_moves=tk.Label(self.entry_frame,text="MOVES : ")
self.label_no_of_moves.grid(row=0,column=0,sticky=tk.N+tk.S+tk.E+tk.W)
self.moves=tk.StringVar()
self.number_of_moves=tk.Entry(self.entry_frame,textvariable=self.moves)
self.number_of_moves.grid(row=0,column=1,sticky=tk.N+tk.S+tk.E+tk.W)
self.label_direction=tk.Label(self.entry_frame,text="DIRECTION : ")
self.label_direction.grid(row=0,column=2,sticky=tk.N+tk.S+tk.E+tk.W)
#Assume Direction to be U D L R you can also use listbox here but i m not using it for saving time
self.dir=tk.StringVar()
self.direction=tk.Entry(self.entry_frame,textvariable=self.dir)
self.direction.grid(row=0,column=3,sticky=tk.N+tk.S+tk.E+tk.W)
self.direction=tk.Button(self.entry_frame,text='GO',command=self.gomoves)
self.direction.grid(row=0,column=4,sticky=tk.N+tk.S+tk.E+tk.W)
for i in range(8):
for j in range(8):
x='label'+str(i)+str(j)
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(3*(j+1))[0]+"7",text=str(i)+str(j))
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
#For updating the grid if window size is changed
self.bind('<Configure>',self.update)
#For initial Player position
self.start_position=str('label'+generate_initial_position())
self.current_position = self.start_position
print (self.current_position)
#initial position removed from positions(avaliable positions)
print (positions)
positions.remove(str(self.start_position))
#selecting treasure chest from remaining positions
self.treasure_chest_positions=random.sample(positions,10)
#removing treasures chest position from positions(avaliable positions)
for i in positions[:]:
if i in self.treasure_chest_positions:
positions.remove(i)
print (self.treasure_chest_positions)
#selecting bandits position from positions(avaliable positions)
self.bandit_positions =random.sample(positions,5)
def sett(self):
self.blink = False
self.guesses = 0
self.end_tick = False
self.tick()
def get_pos(self):
self.used = False
xy = random.randrange(self.gridrange), random.randrange(self.gridrange)
if xy in self.treasure_pos or xy in self.bandit_pos:
self.used = True
while self.used == True:
xy = (random.randrange(self.gridrange), random.randrange(self.gridrange))
if xy not in self.treasure_pos or xy in self.bandit_pos:
self.used = False
return xy
else:
return xy
def gomoves(self,event=None):
print ('GO MOVES')
#Validate Moves so that the values of moves should lie inside the positions avaliable
print (self.moves.get())
print (self.dir.get())
#On moving update the current position variable
#Please deal with the position written in format label(row_no)(column_no) like label01 for row=0 and column=1 it will not be that difficult
current_row= int(self.current_position[5:6])
current_column=int(self.current_position[6:7])
print (current_row , current_column)
#now update the position based on moves if moves are invalid then pop up tkDialogBox search a little on google you will get help from there
#self.current_position =
def key_pressed(self, event):
if event.keysym == "Right" and self.current_pos[1] < 7:
self.current_pos[1] += 1
print("right")
elif event.keysym == "Left" and self.current_pos[1] > 0:
self.current_pos[1] -= 1
print("left")
elif event.keysym == "Up" and self.current_pos[0] > 0:
self.current_pos[0] -= 1
print("up")
elif event.keysym == "Down" and self.current_pos[0] < 7:
self.current_pos[0] += 1
print("down")
elif event.keysym == "Return":
self.process_guess()
self.display_grid()
self.matrix = [["#" for col in range(8)] for row in range(8)] # is here the best place for this?
def check(self):
if self.current_pos_tuple in self.treasures_won:
self.counts = Counter(self.treasures_won)
print (self.counts)
print (self.counts)[self.current_pos_tuple]
if self.current_pos_tuple in self.last_treasure:
self.gold_found -= 10
self.treasures_won.remove(self.current_pos_tuple)
self.guesses -= 1
self.last_treasure.remove(self.current_pos_tuple)
print (self.last_treasure)
if self.counts[self.current_pos_tuple] > 3:
self.treasure_pos.remove(self.current_pos_tuple)
self.bandit_pos.append(self.current_pos_tuple)
print ('someone was here waiting for me')
self.gold_found -= 10
print (self.gold_found)
if self.gold_found >= self.winscore:
print ('you win')
if len(self.treasure_pos) <= 0:
print ('you lose')
def process_guess(self):
self.guesses += 1
self.score_lbl.config(text="Guesses: " + str(self.guesses))
self.current_pos_tuple = tuple(self.current_pos)
print (self.current_pos_tuple)
if self.current_pos_tuple in self.treasure_pos:
self.check()
print ('i think i see something shiney')
self.gold_found += 10
print (self.gold_found)
self.treasures_won.append(self.current_pos_tuple)
self.last_treasure.append(self.current_pos_tuple)
self.end_tick = True
self.gold_lbl.config(text="Gold: " + str(self.gold_found))
self.matrix[self.current_pos_tuple[0]][self.current_pos_tuple[1]] = "$"
self.display_grid()
elif self.current_pos_tuple in self.bandit_pos:
print ('something looks suspisious')
self.gold_found = 0
#if not (self.current_pos[0] == self.treasure_pos[0] and self.current_pos[1] == self.treasure_pos[1]):
#print "NOT HERE"
else:
randinteger = random.randrange(10)
dist = int(round(math.sqrt((self.current_pos[0] - self.treasure_pos[randinteger][0]) ** 2 + (self.current_pos[1] - self.treasure_pos[randinteger][1]) ** 2)))
self.matrix[self.current_pos[0]][self.current_pos[1]] = str(dist)
self.display_grid()
print (' i cant seem to find anything')
self.end_tick = True
def display_grid(self):
'''Displays current visual game state'''
self.island.delete(1.0, tk.END)
m_str = ""
for row in range(len(self.matrix)):
m_str += (" ".join(self.matrix[row]) + "\n")
self.island.insert(1.0, m_str)
def finish(self):
self.matrix[self.treasure_pos[self.current_pos_tuple][0]][self.treasure_pos[self.current_pos_tuple][1]] = "$"
self.display_grid()
self.island.insert(tk.END, " + 10 Gold!")
self.sett()
def update(self,event=None):
print (event.num)
screenx=self.pos_frame.winfo_width()
screeny=self.pos_frame.winfo_height()
for i in range(8):
for j in range(8):
x='label'+str(i)+str(j)
if x in self.treasure_chest_positions:
try:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text='Treasure')
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
except:
print("Treasure error")
elif x in self.bandit_positions:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text='Bandit')
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
elif x==self.current_position:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text='Current')
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
else:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text=str(i)+str(j))
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
def tick(self):
'''timer for blinking cursor'''
if self.blink == False:
self.matrix[self.current_pos[0]][self.current_pos[1]] = "#"
elif self.blink == True:
self.matrix[self.current_pos[0]][self.current_pos[1]] = " "
self.blink = not self.blink
self.display_grid()
if not self.end_tick:
root.after(300, self.tick)
else:
self.sett()
def generate_initial_position():
pos=str(random.randint(0,7))+str(random.randint(0,7))
return pos
root = tk.Tk()
app = Application(root)
#app.master.title('Game')
root.mainloop()
I have a big problem because the code does not want to function while self.gridrange=8 is a tuple it needs to be an integer and I dont know what more you can do to make it an integer
This is the error
()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\Zero Davila\Desktop\new.py", line 110, in letsplay
self.createWidgets()
File "C:\Users\Zero Davila\Desktop\new.py", line 123, in createWidgets
self.matrix = [["#" for col in range(self.gridrange)] for row in range(self.gridrange)]
TypeError: 'tuple' object cannot be interpreted as an integer
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh() This is just so I could post on stack the h's
Your previous posts were incorrect. You did not assign self.gridrange as
self.gridrange = 8
You assign it as:
self.gridops = tk.Listbox(self.opwin, selectmode='SINGLE')
self.gridops.pack()
for i in range(6, 14):
self.gridops.insert(tk.END, i)
self.gridrange = self.gridops.curselection()
If you read through the information for Listbox.curselection() or the actual source code, you'll find that it returns a tuple. Hence your problem.
However, in the future, please create a Minimal, Complete, and Verifiable Example to help in debugging. It would have helped immensely.

Categories