tkinter: pull down menu un-clickable - python

I am creating a tkinter window that updates a matrix multiplication result every second. I wish to use pull down menus to create options for users.
However, since the entire window is re-drawn every second for the matrix update, the pull down menus are re-initialized every second, rendering them pretty much useless.
I am wondering if there is any way around this problem.
Thanks in advance.
from tkinter import *
import time
import sys
def update(a):
root.title("Matrix Multiplication")
menu = Menu(root)
root.config(menu= menu)
subMenu = Menu(menu)
menu.add_cascade(label="Options", menu=subMenu)
subMenu.add_command(label="Opt1...",command=win2)
exitMenu = Menu(menu)
menu.add_cascade(label="Exit", menu=exitMenu)
exitMenu.add_command(label="Exit",command=root.destroy)
X0 = [[8,7,3],[4 ,5,6],[7 ,8,9]]
Y0 = [[5,8,1,2],[6,7,3,0],[4,5,9,1]]
result0 = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
if a == 0:
cpfg = ["magenta", "blue", "green", "purple"]
cpbg = ["white", "white", "white", "white"]
button1 = Button(root, text="Button-1", fg=cpfg[0], bg=cpbg[0])
button2 = Button(root, text="Button-2", fg=cpfg[1], bg=cpbg[1])
button3 = Button(root, text="Button-3", fg=cpfg[2], bg=cpbg[2])
button4 = Button(root, text="Button-4", fg=cpfg[3], bg=cpbg[3])
button1.grid(row=0, column=0)
button2.grid(row=0, column=1)
button3.grid(row=0, column=2)
button4.grid(row=0, column=3)
a = 1
elif a >= 1 and a <= 3:
for b in range(len(X0)):
for c in range(len(X0[0])):
X0[b][c] *= a
a += 1
else:
for b in range(len(X0)):
for c in range(len(X0[0])):
X0[b][c] *= a
a = 1
for i in range(len(X0)):
for j in range(len(Y0[0])):
for k in range(len(Y0)):
result0[i][j] += X0[i][k] * Y0[k][j]
agrp = LabelFrame(root, text="Process-0", padx=5, pady=5)
agrp.grid(row=2, column=1)
for r in range(3):
for c in range(4):
Label(agrp, text=result0[r][c],
borderwidth=4 ).grid(row=r,column=c)
root.after(1000, lambda x = a: update(x))
def win2():
board = Toplevel()
board.title("Message")
S = Scrollbar(board)
T = Text(board, height=4, width=50)
T.pack()
S.pack(side=RIGHT, fill=Y)
T.pack(side=LEFT, fill=Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
quote = """Yep, this is text"""
T.insert(END, quote)
root = Tk()
a=0
update(a)
root.mainloop()

The update method should only calculate and display changes.
def update(a):
if a == 0:
a = 1
elif a >= 1 and a <= 3:
for b in range(len(X0)):
for c in range(len(X0[0])):
X0[b][c] *= a
a += 1
else:
for b in range(len(X0)):
for c in range(len(X0[0])):
X0[b][c] *= a
a = 1
for i in range(len(X0)):
for j in range(len(Y0[0])):
for k in range(len(Y0)):
result0[i][j] += X0[i][k] * Y0[k][j]
for r in range(3):
for c in range(4):
Label(agrp, text=result0[r][c],
borderwidth=4 ).grid(row=r,column=c)
root.after(1000, lambda x = a: update(x))

Related

suggestion with this error ->ValueError: x and y must have same first dimension, but have shapes (10,) and (1, 10)

I am creating a code that allows the user to enter 4 values (a, b, c, and d) for the equation (ax^3+bx^2+cx+d), then the program will output the graph on a window (I am using Tkinter). however, the code for some reason doesn't work.
To explain a bit my code in the input_check process I am outputting a button on a window with a blank box for the input. when the input is entered the program will check if it is the same as 3 (I will be adding more equations after (therefore it will check which equation the user wants), then it should asks for the values of a, b, c, and d, however after than it gives an error.
My code is:
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
root = Tk()
root.title("Maths Plot")
root.geometry("600x500")
root.configure(bg='dark blue')
# this function is just for fun at the moment
def foo():
print('working')
# navigation bar of the website
my_menu = Menu(root)
root.config(menu=my_menu)
# file menu
file_menu = Menu(my_menu)
my_menu.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='notebook', command=foo)
file_menu.add_command(label='open', command=foo)
file_menu.add_separator()
file_menu.add_command(label='copy', command=foo)
# edit menu
edit_menu = Menu(my_menu)
my_menu.add_cascade(label='Edit', menu=edit_menu)
edit_menu.add_command(label='add notebook', command=foo)
edit_menu.add_command(label='cell copy', command=foo)
edit_menu.add_separator()
edit_menu.add_command(label='paste cell', command=foo)
# checking which type of equation the user wants to enter on base of the number inputted
def input_check():
processing = FALSE
answer_int = int(answer1.get())
while processing == FALSE:
if answer_int == 1:
confirmation = Label(root, text="You have inputted the number 1")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=linear_equation())
execution.grid(row=4, column=1)
processing = TRUE
elif answer_int == 2:
confirmation = Label(root, text="You have inputted the number 2")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=quadratic_equation())
execution.grid(row=4, column=1)
processing = TRUE
elif answer_int == 3:
confirmation = Label(root, text="You have inputted the number 3")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=cubic_equation())
execution.grid(row=4, column=1)
processing = TRUE
elif answer_int == 4:
confirmation = Label(root, text="You have inputted the number 4")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=exponential_equation())
execution.grid(row=4, column=1)
processing = TRUE
else:
confirmation = Label(root, text="the answer you inputted is invalid, please try again.")
confirmation.grid(row=3, column=1)
label1 = Label(root, text="enter a number between 1 and 4 ")
answer1 = Entry(root)
button1 = Button(root, text='enter', command=input_check)
label1.grid(row=0, column=0)
answer1.grid(row=0, column=1)
button1.grid(row=1, column=1)
def linear_equation():
print("this is function 1")
def quadratic_equation():
print("this is function 2")
def cubic_equation():
a = ''
b = ''
c = ''
d = ''
# converting the Entries from string to float for future calcuations
def enter_click(event):
global a
global b
global c
global d
a = float(a_entry.get())
b = float(b_entry.get())
c = float(c_entry.get())
d = float(d_entry.get())
# code
x_axis = np.linspace(-10, 10, num=100)
y_base = [a * x_axis ** 3 + b * x_axis ** 2 + c * x_axis + d]
plt.figure(num=0, dpi=120)
plt.plot(x_axis, y_base, label="f(x)", linestyle='--')
plt.legend()
plt.grid(linestyle=':')
plt.xlim([-1000, 1000])
plt.ylim([-1000, 1000])
plt.title('graph')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
a_entry = Entry(root)
a_entry.grid(row=5, column=0)
b_entry = Entry(root)
b_entry.grid(row=6, column=0)
c_entry = Entry(root)
c_entry.grid(row=7, column=0)
d_entry = Entry(root)
d_entry.grid(row=8, column=0)
enter_button = Button(root, text="Enter")
enter_button.grid(row=9, column=0)
enter_button.bind("<Button-1>", enter_click)
enter_button.bind("<Return>", enter_click)
'''def cubic():
return a * x_axis ** 3 + b * x_axis ** 2 + c * x_axis + d'''
def exponential_equation():
print("this is function 4")
root.mainloop()
the error that I keep getting is:
ValueError: x and y must have same first dimension, but have shapes (10,) and (1, 10)
I tried to search online for any information but I didn't find anything usefull.
(I found some solutions that use canvas but I have no idea on how to use it).
Can anyone help me please?

if a user enters a fraction as one of the values of the matrix that it will simply convert to float [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to fill in a matrix, and at the same time if a for example "1/7" get entered that it converts to float ? but it doesn't work
import fractions
import tkinter as tk
from tkinter import *
import numpy as np
import pandas as pd
from fractions import Fraction
from tkinter.font import Font
from PIL import Image, ImageTk
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
import tkinter.messagebox
import os
import sys
#this function contain a small window that you need to put the number of criteria in ,which will be the dimension of the maTRIX , WHEN I FILL THE matrix and click submit for it to be saved it doesn't work
def be():
window = Tk()
window.title("Dimensions ")
window.geometry("300x200")
def variable():
global fn, f
fn = entry_1.get()
f = entry_2.get()
ln = StringVar()
df = []
name = StringVar()
def save():
for entries in range(len(df)):
df[entries] = name.get()
for entries in range(len(df)):
df = df.append({'Critere': df[entries].get()}, ignore_index=True)
print(df)
df
def open_window():
root = tk.Tk()
root.geometry("460x600")
root.title('AHP Application ')
# global f
# f=printent()
# print(f)
for i in range(int(f)):
# c = input("Enter valeur {}: ".format(i))
my_label = Label(root, text="Entrer le critere numero 0{} :".format(i + 1), width=24, font=("bold", 10))
my_label.grid(row=i, column=0, pady=20, padx=5)
my_entry = Entry(root)
my_entry.grid(row=i, column=1, pady=20, padx=5)
df.append(my_entry)
suivant1 = tk.Button(root, text="Suivant", width=8, borderwidth=3, command=hope).place(x=370, y=40)
fermer2 = tk.Button(root, text="Fermer", width=8, borderwidth=3).place(x=370, y=90)
root.mainloop()
label_1 = Label(window, text="Entrer L'Objectif de Votre projet :", width=24, font=("bold", 10))
label_1.place(x=3, y=0)
entry_1 = Entry(window)
entry_1.place(x=100, y=30)
label_2 = Label(window, text="Entrer le nombre de critère :", width=20, font=("bold", 10))
label_2.place(x=3, y=70)
entry_2 = Entry(window)
# Remove default 0
entry_2.delete(0, END)
entry_2.place(x=100, y=100)
suivant = tk.Button(window, text="suivant", borderwidth=3, command=lambda: [variable(), open_window()]).place(x=40,
y=150)
fermer = tk.Button(window, text="fermer", borderwidth=3).place(x=190, y=150)
def hope():
win = Tk()
win.title("Matrix")
win.geometry("700x500")
global f
print(f)
wrapper1 = LabelFrame(win, text="Enter matrix")
wrapper3 = LabelFrame(win, text="Resultats")
wrapper1.pack(fill="both", expand="yes", padx=50, pady=20)
wrapper3.pack(fill="both", expand="yes", padx=20, pady=10)
def convert_to_float(frac_str):
try:
return float(frac_str)
except ValueError:
num, denom = frac_str.split('/')
try:
leading, num = num.split(' ')
whole = float(leading)
except ValueError:
whole = 0
frac = float(num) / float(denom)
return whole - frac if whole < 0 else whole + frac
# empty arrays for your Entrys and StringVars
text_var = []
entries = []
matrix = []
# callback function to get your StringVars
def get_mat():
for i in range(rows):
matrix.append([])
for j in range(cols):
matrix[i].append(convert_to_float (text_var[i][j].get()))
print(matrix)
b = np.array(matrix, dtype=float, order='C')
print(b)
global df2, df, c
index = []
columns = []
for i in range(int(f)):
index.append("critère{}".format(i + 1))
columns.append("critère{}".format(i + 1))
df = pd.DataFrame(data=b, index=index, columns=columns)
print(df)
arr = df.to_numpy()
global c
c = []
for i in range(len(df)):
c.append(np.prod(arr[i].astype(float)))
df2 = pd.DataFrame(data=c, index=range(int(f)), columns=["hi"])
print(df2)
# Label(win, text="Enter matrix :", font=('arial', 10, 'bold'),
# bg="bisque2").place(x=20, y=20)
x2 = 0
y2 = 0
rows = int(f)
cols = int(f)
global df2, df, c
x = np.array(['1.1', '2.2', '3.3'])
for i in range(rows):
# append an empty list to your two arrays
# so you can append to those later
text_var.append([])
entries.append([])
for j in range(cols):
# append your StringVar and Entry
text_var[i].append(StringVar())
entries[i].append(Entry(win, textvariable=text_var[i][j], width=5))
entries[i][j].place(x=80 + x2, y=30 + y2)
x2 += 40
y2 += 30
x2 = 0
button = Button(wrapper1, text="Submit", bg='bisque3', width=15, command=get_mat)
button.place(x=300, y=80)
my_label = Label(wrapper3, text="Lamda Max:", width=24, font=("bold", 10))
my_label.grid(row=0, column=0, pady=20, padx=5)
my_entry = Entry(wrapper3)
my_entry.grid(row=0, column=1, pady=20, padx=5)
# my_entry.insert(0,lamba)
my_label1 = Label(wrapper3, text="Indice de Coherence (CI):", width=24, font=("bold", 10))
my_label1.grid(row=1, column=0, pady=20, padx=5)
my_entry1 = Entry(wrapper3)
my_entry1.grid(row=1, column=1, pady=20, padx=5)
my_label2 = Label(wrapper3, text="Indice de Racio (IC):", width=24, font=("bold", 10))
my_label2.grid(row=2, column=0, pady=20, padx=5)
my_entry2 = Entry(wrapper3)
my_entry2.grid(row=2, column=1, pady=20, padx=5)
def calcule():
global f
df3 = pd.DataFrame(data=c, index=range(int(f)))
df3 = pow(df2, 1 / int(f))
print("df3 is ")
print(df3)
# Somme
Somme = df3.sum()
print("la somme est ")
print(Somme)
# weights
B = df3 / Somme
print(" La matrice des Poids:")
print(B)
# verify if somme of B is 1 , if it is then we are on the right road
Somm = B.sum()
print(Somm)
# consistency check
print("A3")
C = np.dot(df, B)
print(C)
# consistency check
print("A4")
D = C / B
print(D)
# global lamba
# Consistency Index
# lambda
lamba = np.mean(D)
print("the average is ")
print(lamba.to_string())
my_entry.insert(0, lamba.to_string(index=False))
# n = float(n)
CI = (lamba - float(f)) / (float(f) - 1)
print("The consistency Index is")
print(CI.to_string())
my_entry1.insert(0, CI.to_string(index=False))
# consistency ratio
if int(f) == 3:
RI = 0.52
elif int(f) == 4:
RI = 0.89
elif int(f) == 5:
RI = 1.11
elif int(f) == 6:
RI = 1.25
elif int(f) == 7:
RI = 1.35
elif int(f) == 8:
RI = 1.4
elif int(f) == 9:
RI = 1.45
elif int(f) == 10:
RI = 1.49
print("THE RATIO IS :")
print(RI)
CR = float(CI / RI)
my_entry2.insert(0, CR)
if CR < 0.1:
print("Congratulations ,Your criterias are consistent to go ahead \nThe value of consistency ratio is ",
CR,
"which is less han 0.1 ")
else:
print("you need to re-fill the matrix", CR)
button = Button(wrapper3, text="calcule", bg='bisque3', width=15, command=calcule)
button.place(x=500, y=100)
a = IntVar()
win.mainloop()
window.mainloop()
be()
Python actually has a built-in module just for this, which also has support for arbitrary-precision arithmetic and conversion to native floats.
>>> from fractions import Fraction
>>> frac = Fraction("1/7")
>>> float(fract)
0.14285714285714285
Easy to use, and works out-of-the-box. You can also convert it to an integer ratio, in case you want more accuracy than a native float can provide:
>>> frac.as_integer_ratio()
(1, 7)
The reason why float("1/7") doesn't work is because it's not a valid representation of an actual float: it's an integer ratio. Fractions, however, which provides native conversion to-and-from floats, does.

Why my code doesn't execute and how can I execute it?

It got executed once but I add some features and now it doesn't work anymore...
I'm a beginner at python and this is my first project. I'd like to create a game (which works perfectly in the console) but I have some troubles to put it with tkinter
If someone could take a look at this, it would be nice, thanks
Here's my code, I might have mistyped something or I don't know but I'm stucked with this and I can't find the mistake.
import tkinter as tk
from tkinter import Tk, Label, Canvas, Button, Frame, Toplevel, Entry
from random import randrange
num = randrange(0, 50)
money = 100
root = Tk()
root.geometry("750x750")
root["bg"]="beige"
label = Label(root, text="Welcome to the Casino")
label.place(width=180, x=300, y=300)
def csn(x, y, z, i):
if y < 50 and y >= 0 and z <= i :
if y == x:
i += z * 3
return "Well guess. You have %d" %(i)
elif (x % 2 == 0 and y % 2 == 0) or ( x % 2 != 0 and y % 2 != 0):
i += z * 0.5
return "Not so ba. You have %d" %(i)
else:
i -= z
return "Oops, Try again, you loose %d. You now have %d" %(z, i)
else:
return "Try again..."
def submit(master):
label1 = Label(master, text="try again...")
label1.place(width=180, x=300, y=300)
def casino():
top = Toplevel()
top['bg']= 'blue'
top.geometry = ('700x700')
root.withdraw
while money > 0:
try:
number_label = Label(top, text="Chose a nombre : ")
number_label.place(width=180, x=100, y=300)
nentry= Entry(top)
nentry.place(width=180, x=200, y=300)
number = int(nentry.get())
mise_label = Label(top, text="Entre the price you want to mise : ")
mise_label.place(width=180, x=100, y=400)
mise_entry = Entry(top)
mise_entry.place(width=180, x=200, y=400)
mise = float(mise_entry.get())
except ValueError:
btn3 = Button(top, text="submit", command=lambda : submit(top))
btn3.place(width=180, x=300, y=300)
btn = Button(top, text="submit", command= lambda : csn(num, number, mise, money))
btn.place(width=180, x=300, y=500)
else:
label2= Label(top, text="you lose")
label2.place(width=180, x=300, y=500)
btn1 = Button(top, text="Quit", command=top.quit)
btn1.place(width=180, x=300, y=400)
btn2 = Button(top, text="try again", command=casino)
btn2.place(width=180, x=200, y=400)
enter code here
button = Button(root, text="play!", relief='groove', command=casino)
button.place(width=180, x=300, y=400)
root.mainloop()

How can I get the text of a specific button in a list of buttons? I'm using Tkinter

I am currently making a Tic-Tac-Toe game, and I am working on trying to check if someone gets 3 of their pieces in a row, so I can tell them they've won. I'm trying to do that by checking the text of the buttons, to see if I've gotten 3 in a row. However, I don't know how to check the text of a specific button in a list. Does anyone have any ideas, or if there is a better way, can you let me know?
Full Code
import tkinter as tk
class TicTacToe(tk.Tk):
def __init__(self):
super().__init__()
# Vars
self.rounds_played = 0
self.wins = 0
self.losses = 0
self.player = 0
self.turn = 0
self.clicked_buttons = []
# Attributes
self.resizable(False, False)
self.attributes("-toolwindow", True)
# Start
self.game_title = tk.Label(text="Stew's Tic Tac Toe")
self.name_label = tk.Label(text="Choose a name\n(Press the \'Enter\' key to submit)")
self.name_entry = tk.Entry()
self.symbol_label = tk.Label(text="Choose your symbol")
self.symbol_buttons = [tk.Button(text="[X]", command=lambda: self.symbol_select(0)),
tk.Button(text="[O]", command=lambda: self.symbol_select(1))]
self.next = tk.Button(text="Next", command=self.next_button)
self.ready = tk.Button(text="Start", command=self.start_game_button)
self.game_title.grid(row=0)
self.name_label.grid(row=1)
self.name_entry.grid(row=2)
self.name_entry.bind("<Return>", lambda x: self.set_player_name(self.player))
def set_player_name(self, num):
if num == 0:
self.names = [self.name_entry.get()]
if self.names[0] == " ":
self.names = ["Player 1"]
print(self.names[0])
self.symbol_label.grid(row=3,)
self.symbol_buttons[0].grid(row=4, sticky=tk.W, padx=57.5)
self.symbol_buttons[1].grid(row=4, sticky=tk.E, padx=57.5)
elif num == 1:
self.names.append(self.name_entry.get())
if self.names[1] == "" or " ":
self.names.append("Player 2")
self.ready.grid(row=4)
def symbol_select(self, num):
if num == 0:
self.symbol = ["[X]",
"[O]"]
else:
self.symbol = ["[X]",
"[O]"]
self.next.grid(row=5)
def next_button(self):
self.player = 1
self.next.grid_forget()
self.name_entry.delete(0, tk.END)
self.symbol_label.grid_forget()
for x in self.symbol_buttons:
x.grid_forget()
def start_game_button(self):
self.game_title.grid_configure(row=0, column=1, columnspan=3)
self.whos_turn = tk.Label(text="{}\'s turn".format(self.names[0]))
self.whos_turn.grid(row=1, column=1, columnspan=3)
self.ready.grid_forget()
self.name_label.grid_forget()
self.name_entry.grid_forget()
self.game_buttons = [tk.Button(text="[ ]", command=lambda: self.move_update(0)),
tk.Button(text="[ ]", command=lambda: self.move_update(1)),
tk.Button(text="[ ]", command=lambda: self.move_update(2)),
tk.Button(text="[ ]", command=lambda: self.move_update(3)),
tk.Button(text="[ ]", command=lambda: self.move_update(4)),
tk.Button(text="[ ]", command=lambda: self.move_update(5)),
tk.Button(text="[ ]", command=lambda: self.move_update(6)),
tk.Button(text="[ ]", command=lambda: self.move_update(7)),
tk.Button(text="[ ]", command=lambda: self.move_update(8))]
num = 0
for r in range(0,3):
for c in range(0,3):
self.game_buttons[num].grid(row=(r%3 + 2), column=(c%3 + 1))
num = num + 1
self.rounds = tk.Label(text="Rounds Played: {}".format(self.rounds_played))
self.rounds.grid(row=5, column=1, columnspan=3)
def move_update(self, num):
if num not in self.clicked_buttons:
self.clicked_buttons.append(num)
self.turn = self.turn + 1
if self.turn%2 == 1:
self.game_buttons[num].config(text=self.symbol[0])
elif self.turn%2 == 0:
self.game_buttons[num].config(text=self.symbol[1])
# Here is where I am struggling
for x in range(0,8):
if self.game_buttons[x] == "[X]" and self.game_buttons[(x+3)%9]:
if self.game_buttons[(x+6)%9] == "[X]":
print("Winner")
# Here is where it ends
if self.turn == 9:
self.rounds_played = self.rounds_played + 1
self.rounds.configure(text="Rounds Played: {}".format(self.rounds_played))
self.play_again = tk.Button(text="Play Again?", command=self.new_game)
self.play_again.grid(row=6, column=1, columnspan=3)
def new_game(self):
self.turn = 0
game = TicTacToe()
game.mainloop()
Part I am struggling with
for x in range(0,8):
if self.game_buttons[x] == "[X]" and self.game_buttons[(x+3)%9]:
if self.game_buttons[(x+6)%9] == "[X]":
print("Winner")
I realize in this part I'm not finding the text, but I really don't know how to call upon both the specific list item and text.
Calling the element in a list which contains a tkinter Button widget will return the widget itself as if you were calling any other value stored in an element of a list. Meaning that if you wanted the text attribute of the value of the element you could use ["text"] or .cget("text").
See below:
from tkinter import *
root = Tk()
array = [Button(root, text="1"), Button(root, text="2"), Button(root, text="3")]
for i in array:
print(type(i))
print(i.cget("text"))
print(i["text"])

Tkinter wit while loop (python 3)

First I created a window with some buttons and I defined their commands. It all works fine until I add the while loop to check if any button was pressed and then move to the next step. But then the window doesn't show up and the loop is running forever. I would also like to know if there is a better alternative to my code.
from tkinter import *
Round = 0
def blackC():
global Round
print ('0')
x = 0
Round += 1
def brownC():
global Round
print ('1')
x = 1
Round +=1
def redC():
global Round
print ('2')
x = 2
Round += 2
def win():
window = Tk()
window.geometry ('500x500')
window.title('HELLO')
blackB = Button(text = 'BLACK', command=blackC, width=7, height=3, bd=5)
blackB.place(x=1, y=1)
brownB = Button(text = 'BROWN', command=brownC, width=7, height=3, bd=5)
brownB.place(x=86, y=1)
redB = Button(text = 'RED', command=redC, width=7, height=3, bd=5)
redB.place(x=172, y=1)
window.mainloop()
while (Round == 0):
win()
while (Round < 3):
if (Round == 1):
y = x * 10
print ('y')
elif (Round == 2):
y += x
print ('y')
I don't know what exactly you mean by moving to the next step, but you definitely misunderstand how tkninter works. You are missing the parenthesis in the mainloop window.mainloop().
And you don't want to call it in the cycle, because mainloop is a function which is cycle. So you just run it once a time a then it runs infinitely. So your code have to just run once a time function win().
from tkinter import *
Round=0
def button(type):
global Round
print (str(type))
x = type
Round += type
def win():
window = Tk()
window.geometry ('500x500')
window.title('HELLO')
blackB = Button(text = 'BLACK', command=lambda: button(0), width=7, height=3, bd=5)
blackB.place(x=1, y=1)
brownB = Button(text = 'BROWN', command=lambda: button(1), width=7, height=3, bd=5)
brownB.place(x=86, y=1)
redB = Button(text = 'RED', command=lambda: button(2), width=7, height=3, bd=5)
redB.place(x=172, y=1)
window.mainloop
win()
You have asked for better code, so I have rewritten your buttons func for a one, which just takes an parametr of type and call it as a lambda function (take a look: http://www.diveintopython.net/power_of_introspection/lambda_functions.html.
For a larger projects it is better to have tkinter window as a class, but in this is it enough.

Categories

Resources