How can I stack multiple frames in Tkinter - python

For my project, I need to create a GUI using Tkinter. I wanted to divide it into 4 different frames, each with different background colors. However, when I do this, only the first frame's background color is shown. I attached my code below as well as a screenshot of the output I'm getting.
from Tkinter import *
import tkMessageBox
root = Tk()
root.geometry("950x800")
root.configure(background="black")
def test():
print("this is a test")
# *****Frames*****
fileFrame = Frame(root)
fileFrame.configure(background="yellow")
fileFrame.pack()
attributeFrame = Frame(root)
attributeFrame.configure(background="red")
attributeFrame.pack()
constraintFrame = Frame(root)
constraintFrame.configure(background="purple")
constraintFrame.pack()
preferenceFrame = Frame(root)
preferenceFrame.configure(background="blue")
preferenceFrame.pack()
# *****File Frame*****
label_1 = Label(fileFrame, text="Enter Attributes file name:", anchor="e",
bg="red", font="Times 25", width=25, height=1)
label_2 = Label(fileFrame, text="Enter hard constraints file name:",
anchor="e", bg="blue", fg="yellow", font="Times 25", width=25, height=1)
label_3 = Label(fileFrame, text="Enter preferences file name:",
anchor="e", bg="purple", fg="green", font="times 25", width=25, height=1)
entry_1 = Entry(fileFrame, font="Times 25")
entry_2 = Entry(fileFrame, font="Times 25")
entry_3 = Entry(fileFrame, font="Times 25")
button_1 = Button(fileFrame, text="Submit", bg="red", font="Times 20")
button_2 = Button(fileFrame, text="Submit", bg="blue", fg="yellow",
font="Times 20")
button_3 = Button(fileFrame, text="Submit", bg="purple", fg="green",
font="Times 20")
label_1.grid(row=0, padx=5, pady=5)
entry_1.grid(row=0, column=1)
button_1.grid(row=0, column=2, padx=5, pady=5)
label_2.grid(row=1, padx=5, pady=5)
entry_2.grid(row=1, column=1)
button_2.grid(row=1, column=2, padx=5, pady=5)
label_3.grid(row=2, padx=5, pady=5)
entry_3.grid(row=2, column=1)
button_3.grid(row=2, column=2, padx=5, pady=5)
# *****Attribute Frame*****
label_Attribute_header = Label(attributeFrame, text="Attributes:",
bg="red", font="Times 25", width=25, height=1)
label_Attribute_header.pack()
# *****Constraint Frame*****
label_Constraint_header = Label(constraintFrame, text="Hard Constraints:",
bg="purple", fg="green", font="Times 25", width=25, height=1)
label_Constraint_header.pack()
# *****Preference Frame*****
label_Preference_header = Label(preferenceFrame, text="Preferences:",
bg="blue", fg="yellow", font="Times 25", width=25, height=1)
label_Preference_header.pack()
root.mainloop()
I expect there to be 4 different frames, all stacked on top of each other with different background colors, but instead only the first frame has a background color. Can somebody explain to me why this is and how I should go about fixing this? Thanks

Your frames are there. The bottom three frames have fewer things in them and you haven't given them any padding. The frame shrinks to fit, so when you just have one item, you won't see the frames.
You can easily see the frames if you do one of two things:
First, you can request that the frames fill their parent window in the x direction. When you do this, you'll see them:
fileFrame.pack(fill="x")
attributeFrame.pack(fill="x")
constraintFrame.pack(fill="x")
preferenceFrame.pack(fill="x")
Second, instead of or in addition to that, you can give padding around the labels in the bottom frames. That will let the frame colors appear.
label_Attribute_header.pack(padx=20, pady=20)
...
label_Constraint_header.pack(padx=20, pady=20)
...
label_Preference_header.pack(padx=20, pady=20)

Related

Python TKinter Mac: Buttons layout strangely & click don't work

Python TKinter Mac: Buttons layout strangely and when a button is clicked it looks the same (as if it hadn't been clicked) however I didn't check to see if the button worked.
and the space is a textbook
the Mac version is: a 2017 iMac running Monterey 12.4
import tkinter as tk
window = tk.Tk()
window.geometry("500x500")
window.title("Stock Watchlist & Logger")
label = tk.Label(window, text="Tester", font=('Ariel', 18))
label.pack(padx=20, pady=20)
textbox = tk.Text(window, height=3, font=('Ariel', 16))
textbox.pack(padx=10, pady=10)
numbuttframe = tk.Frame(window)
numbuttframe.columnconfigure(0, weight=1)
yesnobuttframe = tk.Frame(window)
yesnobuttframe.columnconfigure(1, weight=1)
button1 = tk.Button(numbuttframe, text="1", font=('Arial', 18))
button1.grid(row=0, column=0, sticky=tk.W+tk.E)
button2 = tk.Button(numbuttframe, text="2", font=('Arial', 18))
button2.grid(row=0, column=1, sticky=tk.W+tk.E)
button3 = tk.Button(numbuttframe, text="3", font=('Arial', 18))
button3.grid(row=0, column=2, sticky=tk.W+tk.E)
button4 = tk.Button(numbuttframe, text="4", font=('Arial', 18))
button4.grid(row=0, column=3, sticky=tk.W+tk.E)
button5 = tk.Button(numbuttframe, text="5", font=('Arial', 18))
button5.grid(row=0, column=4, sticky=tk.W+tk.E)
button6 = tk.Button(numbuttframe, text="6", font=('Arial', 18))
button6.grid(row=0, column=5, sticky=tk.W+tk.E)
yesbutton = tk.Button(yesnobuttframe, text="Yes", font=('Arial', 18))
yesbutton.grid(row=0, column=0, sticky=tk.W+tk.E)
nobutton = tk.Button(yesnobuttframe, text="No", font=('Arial', 18))
nobutton.grid(row=0, column=1, sticky=tk.W+tk.E)
numbuttframe.pack(fill='x')
yesnobuttframe.pack(fill='x')
if button1:
print("CELEBRATE!")
window.mainloop()
You set the weight to two cells weight=1 , so they expanded, since the rest have a default weight of 0. Since I don’t see your grid - the buttons are placed in frames one after the other, suggest using the pack method. And shortened your code a bit. The buttons won't work yet, because they don't have a command = call. Complex variable names in Python are usually written with an underscore.
import tkinter as tk
FONT = ('Ariel', 18)
window = tk.Tk()
window.geometry("500x500")
window.title("Stock Watchlist & Logger")
lbl = tk.Label(window, text="Tester", font=FONT)
lbl.pack(padx=20, pady=20)
text_box = tk.Text(window, height=3, font=('Ariel', 16))
text_box.pack(padx=10, pady=10)
num_btn = tk.Frame(window)
yes_no_btn = tk.Frame(window)
num_btn.pack(fill='x')
yes_no_btn.pack(fill='x')
buttons = []
for i in range(1, 7):
btn = tk.Button(num_btn, text=f"{i}", font=FONT)
btn.pack(side="left", fill='x', expand=True)
buttons.append(btn)
yes_btn = tk.Button(yes_no_btn, text="Yes", font=FONT)
yes_btn.pack(side="left", fill='x', expand=True)
no_btn = tk.Button(yes_no_btn, text="No", font=FONT)
no_btn.pack(side="left", fill='x', expand=True)
window.mainloop()

I'm getting an indent error in Eclipse compiler, anyone have any ideas as to why?

I'm getting an indent error in my Eclipse compiler, I have marked the specific line below on for where the error is. Anyone have any idea on the fix? It's for an assignment at school and I have no idea on a fix and I'm at a complete, absolute loss. I would appreciate anyone's tips. "Write a GUI based program that simulates a simple pocket calculator. The GUI displays a single entry field for output (I would suggest to make it a read only field). It should present the user with 10 numeric buttons from 0 to 9 and seven function keys for +, -, *, /, C (C is for clearing the display), . (decimal point) and =. = is to calculate the correct answer. If there is an error like divide by zero the entry field should display ERR or Error. Values in the entry field will build a string that will be converted to a float for calculation." This is the assignment I have to complete.
from tkinter import *
from tkinter import font as tkFont # for convenience
expression = ""
# functions
def input_number(number, equation):
global expression
# concatenation of string
expression = expression + str(number)
equation.set(expression)
def clear_input_field(equation):
global expression
expression = ""
# setting empty string in the input field
equation.set("Enter the expression")
def evaluate(equation):
global expression
# trying to evaluate the expression
try:
result = str(eval(expression))
equation.set(result)
expression = ""
except:
equation.set("Error: Divide by zero")
expression = ""
def main():
# creating main window
tk = Tk()
# setting the title
tk.title("Calculator")
# seting the size of window
tk.geometry("570x500")
# varible class instantiation
equation = StringVar()
# input field for the expression
input_field = Entry(tk, textvariable=equation)
input_field.place(height=100)
input_field.grid(columnspan=4, ipadx=200, ipady=10)
equation.set("Enter the expression")
myFont = tkFont.Font(family='Helvetica', size=12, weight='bold')
input_field['font']=myFont
# creating buttons and placing them at respective positions
_1 = Button(tk, text='1', fg='black', bg='red', bd=2, command=lambda: input_number(1, equation), height=5, width=10) #I'm getting an error on this line
_1['font'] = myFont
_1.grid(row=2, column=0)
_2 = Button(tk, text='2', fg='black', bg='red', bd=2, command=lambda: input_number(2, equation), height=5, width=10)
_2.grid(row=2, column=1)
_3 = Button(tk, text='3', fg='black', bg='red', bd=2, command=lambda: input_number(3, equation), height=5, width=10)
_3.grid(row=2, column=2)
_4 = Button(tk, text='4', fg='black', bg='red', bd=2, command=lambda: input_number(4, equation), height=5, width=10)
_4.grid(row=3, column=0)
_5 = Button(tk, text='5', fg='black', bg='red', bd=2, command=lambda: input_number(5, equation), height=5, width=10)
_5.grid(row=3, column=1)
_6 = Button(tk, text='6', fg='black', bg='red', bd=2, command=lambda: input_number(6, equation), height=5, width=10)
_6.grid(row=3, column=2)
_7 = Button(tk, text='7', fg='black', bg='red', bd=2, command=lambda: input_number(7, equation), height=5, width=10)
_7.grid(row=4, column=0)
_8 = Button(tk, text='8', fg='black', bg='red', bd=2, command=lambda: input_number(8, equation), height=5, width=10)
_8.grid(row=4, column=1)
_9 = Button(tk, text='9', fg='black', bg='red', bd=2, command=lambda: input_number(9, equation), height=5, width=10)
_9.grid(row=4, column=2)
_0 = Button(tk, text='0', fg='black', bg='red', bd=2, command=lambda: input_number(0, equation), height=5, width=10)
_0.grid(row=5, column=0)
plus = Button(tk, text='+', fg='black', bg='red', bd=2, command=lambda: input_number('+', equation), height=5, width=10)
plus.grid(row=2, column=3)
minus = Button(tk, text='-', fg='black', bg='red', bd=2, command=lambda: input_number('-', equation), height=5, width=10)
minus.grid(row=3, column=3)
multiply = Button(tk, text='*', fg='black', bg='red', bd=2, command=lambda: input_number('*', equation), height=5, width=10)
multiply.grid(row=4, column=3)
divide = Button(tk, text='/', fg='black', bg='red', bd=2, command=lambda: input_number('/', equation), height=5, width=10)
divide.grid(row=5, column=3)
equal = Button(tk, text='=', fg='black', bg='red', bd=2, command=lambda: evaluate(equation), height=5, width=10)
equal.grid(row=5, column=2)
_1['font'] = myFont
_2['font'] = myFont
_3['font'] = myFont
_4['font'] = myFont
_5['font'] = myFont
_6['font'] = myFont
_7['font'] = myFont
_8['font'] = myFont
_9['font'] = myFont
_0['font'] = myFont
plus['font'] = myFont
minus['font'] = myFont
multiply['font'] = myFont
divide['font'] = myFont
equal['font'] = myFont
clear = Button(tk, text='Clear', fg='black', bg='red', bd=2, command=lambda: clear_input_field(equation), height=5, width=10)
clear.grid(row=5, column=1)
clear['font']=myFont
# showing the GUI continue
tk.mainloop()
if __name__ == '__main__':
main()```
The line you've highlighted, and the following lines, are indented by an extra step - make sure they line up with the line above, as they aren't inside another block (e.g a function or an if statement)

How can I read from a file where the name is given by an entry widget in Tkinter?

I'm new to python and even newer to Tkinter. I'm trying to have the user enter the filename in an entry widget and hit a button that outputs the contents of the entered file to the console. The problem occurs in the attributeFileName() method (line 7) after button_1 (line 46) is pressed. Here is my code below:
from Tkinter import *
import tkMessageBox
root = Tk()
root.configure(background="black")
def attributeFileName():
try:
f = open(entry_1.get(), 'r') # Tries to open the file entered by the
except IOError:
print ("Cannot open", entry_1.get()) # If the file cannot be opened,
report it back to the user
for line in f:
print line
f.close()
def constraintFileName():
print(entry_2.get())
def preferenceFileName():
print(entry_3.get())
# *****Frames*****
fileFrame = Frame(root)
fileFrame.configure(background="black")
fileFrame.pack(pady=50)
attributeFrame = Frame(root)
attributeFrame.configure(background="red")
attributeFrame.pack(pady=5)
constraintFrame = Frame(root)
constraintFrame.configure(background="blue")
constraintFrame.pack(pady=5)
preferenceFrame = Frame(root)
preferenceFrame.configure(background="#51006F")
preferenceFrame.pack()
# *****File Frame*****
label_1 = Label(fileFrame, text="Enter Attributes file name:", anchor="e",
bg="red", font="Times 25", width=25, height=1)
label_2 = Label(fileFrame, text="Enter hard constraints file name:",
anchor="e", bg="blue", fg="yellow", font="Times 25", width=25, height=1)
label_3 = Label(fileFrame, text="Enter preferences file name:",
anchor="e", bg="#51006F", fg="#45FFF4", font="times 25", width=25,
height=1)
entry_1 = Entry(fileFrame, font="Times 25")
entry_2 = Entry(fileFrame, font="Times 25")
entry_3 = Entry(fileFrame, font="Times 25")
button_1 = Button(fileFrame, text="Submit", bg="red", font="Times 20",
command=attributeFileName)
button_2 = Button(fileFrame, text="Submit", bg="blue", fg="yellow",
font="Times 20", command=constraintFileName)
button_3 = Button(fileFrame, text="Submit", bg="#51006F", fg="#45FFF4",
font="Times 20", command=preferenceFileName)
label_1.grid(row=0, column=0, padx=5, pady=5)
entry_1.grid(row=0, column=1)
button_1.grid(row=0, column=2, padx=5, pady=5)
label_2.grid(row=1, column=0, padx=5, pady=5)
entry_2.grid(row=1, column=1)
button_2.grid(row=1, column=2, padx=5, pady=5)
label_3.grid(row=2, column=0, padx=5, pady=5)
entry_3.grid(row=2, column=1)
button_3.grid(row=2, column=2, padx=5, pady=5)
# *****Attribute Frame*****
attributeHeaderFrame = Frame(attributeFrame)
attributeHeaderFrame.configure(background="red")
attributeHeaderFrame.grid(row=0)
attributeDataFrame = Frame(attributeFrame)
attributeDataFrame.configure(background="red")
attributeDataFrame.grid(row=1)
attributeListFrame = Frame(attributeFrame)
attributeListFrame.configure(background="red")
attributeListFrame.grid(row=2, pady=10)
label_Attribute_header = Label(attributeHeaderFrame, text="Attributes",
bg="red", font="Times 25", width=25, height=1)
attribute_Name = Label(attributeDataFrame, text="Name:", bg="red",
font="Times 20")
entry_Attribute_Name = Entry(attributeDataFrame, font="Times 20")
label_Colon = Label(attributeDataFrame, text=":", bg="red", font="Times
20")
label_Comma = Label(attributeDataFrame, text=",", bg="red", font="Times
25")
entry_Attribute1 = Entry(attributeDataFrame, font="Times 20")
entry_Attribute2 = Entry(attributeDataFrame, font="Times 20")
attribute_add = Button(attributeDataFrame, text="+", bg="black",
fg="white", font="Times 15")
list = Listbox(attributeListFrame, height=15, width=172)
scroll = Scrollbar(attributeListFrame, command=list.yview)
list.configure(yscrollcommand = scroll.set)
list.pack(side=LEFT)
scroll.pack(side=RIGHT, fill=Y)
label_Attribute_header.pack()
attribute_Name.grid(row=0, column=0, padx=5, pady=5, sticky="W")
entry_Attribute_Name.grid(row=0, column=1, sticky="W")
label_Colon.grid(row=0, column=2, sticky="W")
entry_Attribute1.grid(row=0, column=3, sticky="W", padx=(50,0))
label_Comma.grid(row=0, column=4, sticky="W")
entry_Attribute2.grid(row=0, column=5, sticky="W")
attribute_add.grid(row=0, column=6, padx=5, pady=5, sticky="W")
# *****Constraint Frame*****
constraintHeaderFrame = Frame(constraintFrame)
constraintHeaderFrame.configure(background="blue")
constraintHeaderFrame.grid(row=0)
constraintDataFrame = Frame(constraintFrame)
constraintDataFrame.configure(background="blue")
constraintDataFrame.grid(row=1, pady=10)
constraintListFrame = Frame(constraintFrame)
constraintListFrame.configure(background="blue")
constraintListFrame.grid(row=2, pady=10)
label_Constraint_header = Label(constraintHeaderFrame, text="Hard
Constraints", bg="blue", fg="yellow", font="Times 25")
label_Constraints = Label(constraintDataFrame, text="Constraint:",
bg="blue", fg="yellow", font="Times 20",)
entry_Constraints = Entry(constraintDataFrame, font="Times 20")
constraint_add = Button(constraintDataFrame, text="+", bg="black",
fg="white", font="Times 15")
label_Constraint_header.pack()
label_Constraints.grid(row=0)
entry_Constraints.grid(row=0, column=1)
constraint_add.grid(row=0, column=2, padx=15)
list = Listbox(constraintListFrame, height=15, width=172)
scroll = Scrollbar(constraintListFrame, command=list.yview)
list.configure(yscrollcommand = scroll.set)
list.pack(side=LEFT)
scroll.pack(side=RIGHT, fill=Y)
# *****Preference Frame*****
preferenceHeaderFrame = Frame(preferenceFrame)
preferenceHeaderFrame.configure(background="#51006F")
preferenceHeaderFrame.grid(row=0)
preferenceDataFrame = Frame(preferenceFrame)
preferenceDataFrame.configure(background="#51006F")
preferenceDataFrame.grid(row=1, pady=10)
preferenceListFrame = Frame(preferenceFrame)
preferenceListFrame.configure(background="#51006F")
preferenceListFrame.grid(row=2, pady=10)
label_Preference_header = Label(preferenceHeaderFrame, text="Preferences",
bg="#51006F", fg="#45FFF4", font="Times 25")
label_preference = Label(preferenceDataFrame, text="Preference:",
bg="#51006F", fg="#45FFF4", font="Times 20",)
entry_preference = Entry(preferenceDataFrame, font="Times 20")
preference_add = Button(preferenceDataFrame, text="+", bg="black",
fg="white", font="Times 15")
label_Preference_header.pack()
label_preference.grid(row=0)
entry_preference.grid(row=0, column=1)
preference_add.grid(row=0, column=2, padx=15)
list = Listbox(preferenceListFrame, height=15, width=172)
scroll = Scrollbar(preferenceListFrame, command=list.yview)
list.configure(yscrollcommand = scroll.set)
list.pack(side=LEFT)
scroll.pack(side=RIGHT, fill=Y)
root.mainloop()
My Output:
I expect the name of the file to be read from the entry widget and the file contents printed out to the console. However, instead an Exception is thrown. Here is the stack trace:
('Cannot open', 'test.txt')
Exception in Tkinter callback
Traceback (most recent call last):
File "Tkinter.py", line 1542, in __call__
return self.func(*args)
File "gui.py", line 13, in attributeFileName
for line in f:
UnboundLocalError: local variable 'f' referenced before assignment
Can somebody explain to me what this means, why I'm getting this error, and most importantly how to fix it? Thanks
In this function:
def attributeFileName():
try:
f = open(entry_1.get(), 'r') # Tries to open the file entered by the
except IOError:
print ("Cannot open", entry_1.get()) # If the file cannot be opened, report it back to the user
for line in f:
print (line)
f.close()
If an exception is caught, f is undefined and result in your unbound error. Simply move the for loop and close inside the try statement:
def attributeFileName():
try:
f = open(entry_1.get(), 'r')
for line in f:
print(line)
f.close()
except IOError:
print ("Cannot open", entry_1.get())

Python/Tkinter Frontend Frame

When opened normally
Fullscreen
i'm working on my first ever project, and i'm using python/tkinter. i've come up with this design(above) but i can't make it responsive.
i want the bottom section to stay the same but i want to extend the top part through the bottom.
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack(side=TOP, fill=BOTH)
scrollbar = Scrollbar(topFrame)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(topFrame)
listbox.pack(fill=BOTH)
for i in range(100):
listbox.insert(END, i)
#attaching list and scroll
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)
#bottom frame
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM, fill=X)
#bottom laft frame
b_leftFrame = Frame(bottomFrame)
b_leftFrame.pack(side=LEFT, fill=X)
#defining label
label1 = Label(b_leftFrame, text="Title")
label1.grid(row=0, column=0, sticky=E)
label2 = Label(b_leftFrame, text="Author")
label2.grid(row=0, column=2, sticky=E)
label3 = Label(b_leftFrame, text="Publisher")
label3.grid(row=0, column=4, sticky=E)
label4 = Label(b_leftFrame, text="Year")
label4.grid(row=0, column=6, sticky=E)
label5 = Label(b_leftFrame, text="Translator")
label5.grid(row=0, column=8, sticky=E)
#defining labels
title_text =StringVar()
entry1 = Entry(b_leftFrame, textvariable=title_text)
entry1.grid(row=0, column=1)
author_text =StringVar()
entry2 = Entry(b_leftFrame, textvariable=author_text)
entry2.grid(row=0, column=3)
publisher_text =StringVar()
entry3 = Entry(b_leftFrame, textvariable=publisher_text)
entry3.grid(row=0, column=5)
year_text =StringVar()
entry4 = Entry(b_leftFrame, textvariable=year_text)
entry4.grid(row=0, column=7)
translator_text =StringVar()
entry4 = Entry(b_leftFrame, textvariable=translator_text)
entry4.grid(row=0, column=9)
#bottom right
b_rightFrame = Frame(bottomFrame)
b_rightFrame.pack(side=RIGHT)
#buttons
b1=Button(b_rightFrame, text="View All", width=12)
b1.grid(row=2, column=3)
b1=Button(b_rightFrame, text="Search Entry", width=12)
b1.grid(row=3, column=3)
b1=Button(b_rightFrame, text="Add Entry", width=12)
b1.grid(row=4, column=3)
b1=Button(b_rightFrame, text="Update selected", width=12)
b1.grid(row=5, column=3)
b1=Button(b_rightFrame, text="Delete selected", width=12)
b1.grid(row=6, column=3)
b1=Button(b_rightFrame, text="Close", width=12)
b1.grid(row=7, column=3)
root.mainloop()
The problem here is that the topFrame widget, which contains the Listbox, is not taking all the available space.
Try replacing your:
topFrame.pack(fill=BOTH)
with:
topFrame.pack(fill=BOTH, expand=YES)
This will make the topFrame expand once you maximize the window.
Also, in order to make the listbox expand as well, replace your
listbox.pack(fill=BOTH)
with:
listbox.pack(fill=BOTH, expand=YES)

How do I stop a button command when another button is clicked in python?

So my intention is when the user clicks one of the buttons, for the rest of the other buttons not to perform anything even when clicked, so basically to stop the buttons from performing their commands when the user clicks them ONLY if they have clicked in another button previously, I don't know if I expressed myself well so I am sorry if I dind't but here's my code:
from tkinter import *
import random
screen = Tk()
ticket = random.randint(1,3)
def test():
def test1():
if ticket == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=0, column=0, sticky="w")
else:
button_2 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_2.grid(row=0, column=0, sticky="w")
def test2():
if ticket == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=0, column=1, sticky="w")
else:
button_4 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_4.grid(row=0, column=1, sticky="w")
def test3():
if ticket == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=0, column=2, sticky="w")
else:
button_6 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_6.grid(row=0, column=2, sticky="w")
ticket = random.randint(1,3)
button1 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=0, column=0, sticky="w")
button1 = 1
button2 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=0, column=1, sticky="w"+"e"+"n"+"s")
button2 = 2
button3 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=0, column=2, sticky="e")
button3 = 3
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=1, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
You can set the state of the other Buttons to DISABLED to grey them out and prevent clicks. This would be the ideal place to use a subclass that keeps track of its instances.
from tkinter import *
import random
screen = Tk()
class MykoButton(Button):
instances = []
def __init__(self, master=None, **kwargs):
super().__init__(master, command=self.run, **kwargs)
self.instances.append(self)
def run(self):
for button in self.instances:
if button is not self:
button.config(state=DISABLED)
if random.randint(1,3) == 1:
self.config(text="RIP", fg="white", bg="red") # update the button
else:
self.config(text="+1", fg="white", bg="green")
def test():
for i in range(3):
button = MykoButton(screen, text="1", fg="white", bg="blue", width=15, height=2)
button.grid(row=0, column=i)
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=1, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
Also, note that I changed your code to update the clicked button, rather than put a new button on top of it.

Categories

Resources