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

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()

Related

number guessing function in python using tkinter

So ive been trying to create a program of number guessing using tkinter but it isn't working proper like after first attempt it shows 0 attempts while ive declared 3 im attaching the source code here for better understanding the problem i feel is that its not taking attemptsas a global scope so its not being accessed by the other functions
import random
from tkinter import *
random_number = random.randint(0, 999)
root = Tk()
root.geometry('500x500')
root.title("Number guessing game")
label_0 = Label(root, text="Number guessing game", width=20, font=("bold", 20))
label_0.place(x=90, y=53)
label_1 = Label(root, text="Enter number", width=20, font=("bold", 10))
label_1.place(x=80, y=150)
entry_1 = Entry(root)
entry_1.place(x=240, y=150)
def printAttempts(_attempts):
attempt_string = "Attempt left: " + str(_attempts)
label_attempt = Label(root,
text=attempt_string,
width=20,
font=("bold", 20))
label_attempt.place(x=90, y=100)
printAttempts(3)
def printMessage(msg):
_message = Label(root, text=msg, width=50, font=("bold", 10))
_message.place(x=80, y=200)
def onSubmit():
attempts = 3
guessed_number = entry_1.get()
guessed_number = int(guessed_number)
while attempts != 0:
if (guessed_number == random_number):
printMessage("Horray you just got it Right!")
attempts = 0
break
else:
attempts -= 1
printMessage("You got it wrong :(")
if (guessed_number > random_number):
printMessage("Your guess number is greater than lucky number")
else:
printMessage("Your guess number is less than lucky number")
printAttempts(attempts)
continue
if (attempts == 0):
printMessage("No attempts left, try again later")
break
Button(root, text='Submit', width=20, bg='brown', fg='white',
command=onSubmit).place(x=180, y=380)
root.mainloop()
Removing the while loop fixes the problem.
Also have to make the attempts variable global.
Also have to modify the if statements.
Added some print statements for debugging.
comment:
prefer an alias import tkinter as tk to the wildcard from tkinter import *. it is easier to see where functions come from.
This works:
import random
from tkinter import *
attempts = 3
random_number = random.randint(0, 999)
root = Tk()
root.geometry('500x500')
root.title("Number guessing game")
label_0 = Label(root, text="Number guessing game", width=20, font=("bold", 20))
label_0.place(x=90, y=53)
label_1 = Label(root, text="Enter number", width=20, font=("bold", 10))
label_1.place(x=80, y=150)
entry_1 = Entry(root)
entry_1.place(x=240, y=150)
def printAttempts(_attempts):
attempt_string = "Attempt left: " + str(_attempts)
label_attempt = Label(root,
text=attempt_string,
width=20,
font=("bold", 20))
label_attempt.place(x=90, y=100)
printAttempts(3)
def printMessage(msg):
_message = Label(root, text=msg, width=50, font=("bold", 10))
_message.place(x=80, y=200)
def onSubmit():
global attempts
print('attempts', attempts)
guessed_number = entry_1.get()
guessed_number = int(guessed_number)
if attempts != 0:
print('the guess', guessed_number)
print('the random', random_number)
if (guessed_number == random_number):
printMessage("Horray you just got it Right!")
attempts = 0
print(attempts)
else:
print('removing one attempt')
attempts = attempts - 1
printMessage("You got it wrong :(")
if (guessed_number > random_number):
printMessage("Your guess number is greater than lucky number")
print('too high', attempts)
else:
printMessage("Your guess number is less than lucky number")
print('too low', attempts)
if (attempts == 0):
printMessage("No attempts left, try again later")
print('run out', attempts)
printAttempts(attempts)
Button(root, text='Submit', width=20, bg='brown', fg='white',
command=onSubmit).place(x=180, y=380)
root.mainloop()
result:

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?

Tkinter while loop guess game

# Tkinter guessing game
from tkinter import *
import random
window = Tk()
# Bot Generator
bot = random.randint(1, 20+1)
print(bot)
def submit():
tries = 5
while tries >= 0:
e1 = (int(guessE.get()))
if e1 == bot:
print("You win")
break
elif e1 != bot:
print("Try again")
tries -= 1
break
def clear():
guessE.delete(0, "end")
# Guess Label
guessL = Label(window, text="Guess a number (between 1 and 20}")
guessL.place(x=75, y=50)
# Guess Entry
guessE = Entry(window, width=25, bg="lightgrey")
guessE.place(x=95, y= 80)
# Submit Button
submitBtn = Button(window, width=10, height=2, text="Submit", command=submit)
submitBtn.place(x=85, y=115)
# Clear Button
clearBtn = Button(window, width=10, height=2, text="Clear", command=clear)
clearBtn.place(x=175, y=115)
window.geometry("350x350")
window.resizable(0, 0)
window.attributes("-topmost", True)
window.mainloop()
I am trying to create a guessing game with Tkinter, I have created all the entries and labels, the clear button is working. I am struggling with creating a while loop, I need the program to stop accepting submitted entries once 5 tries have been used. Any ideas on how I can solve this?
Like already mentioned by #Paul Rooney, i also think that a while loop is a bad design for this. However, here is a working example with a global variable and some minor changes (disabling entry and button when 0 tries are reached):
# Tkinter guessing game
from tkinter import *
import random
window = Tk()
# Bot Generator
bot = random.randint(1, 20+1)
print(bot)
# define outside of function to not overwrite each time
tries = 5
def submit():
global tries # to make tries a global variable
while tries > 0: # this matches your tries amount correctly
e1 = (int(guessE.get()))
if e1 == bot:
print("You win")
break
elif e1 != bot:
print("Try again")
tries -= 1
break
# print status, disable the widgets
if tries == 0:
print("No more tries left")
guessE.configure(state="disabled")
submitBtn.configure(state="disabled")
def clear():
guessE.delete(0, "end")
# Guess Label
guessL = Label(window, text="Guess a number (between 1 and 20}")
guessL.place(x=75, y=50)
# Guess Entry
guessE = Entry(window, width=25, bg="lightgrey")
guessE.place(x=95, y= 80)
# Submit Button
submitBtn = Button(window, width=10, height=2, text="Submit", command=submit)
submitBtn.place(x=85, y=115)
# Clear Button
clearBtn = Button(window, width=10, height=2, text="Clear", command=clear)
clearBtn.place(x=175, y=115)
window.geometry("350x350")
window.resizable(0, 0)
window.attributes("-topmost", True)
window.mainloop()

How can i fix this Textwidget in Tkinter?

Why is y not output twice if you type 2 in the text field?
Thanks for help
from tkinter import *
root = Tk()
root.geometry("500x450")
def copy():
y = txt.get(1.0, END)
print(y)
if y == "2":
print("Check")
txt = Text(root, width=60, height=20, font=("Arial", 12))
txt.place(x=0, y=0)
btn = Button(root, text="Copy", command=copy)
btn.place(x=250, y=400)
mainloop()
because there is a hidden \n here. If you change your if to if y == "2\n": it will print check

{self.tk.call( _tkinter.TclError: unknown option "-command"} error

I'm trying to write calculator code which contains only plus mode and minus mode and BMI calculator. I've tried everything I know so far but I can't figure it out that why my code is unable to use
Here is my Bmi code:
from tkinter import *
def bmi():
kg = int(box1.get())
m = int(box2.get())
result =(kg)/(m^2)
result.configure(result).grid(row=2,column=1)
return
root = Tk()
root.option_add("*font", "impact 16")
Label(root, text= "wight(kg.)").grid(row=0,column=0)
box1 = Entry(root).grid(row=0,column=1)
Label(root, text= "hight(m.)").grid(row=1,column=0)
box2 = Entry(root).grid(row=1,column=1)
Label(root, text= "BMI",command=bmi).grid(row=2,column=0)
Button(root, text= "calculate").grid(row=3,columnspan=2)
root.mainloop()
and there is my calculator code
import tkinter as tk
def show_output():
number = int(number1_input.get())
if number == 1:
output_label.configure(text="plus")
number0_ask = tk.Label(master=window, text='input first number')
number0_input = tk.Entry(master=window,width= 15)
number2_ask = tk.Label(master=window, text='input second number')
number2_input = tk.Entry(master=window, width=15)
sum = int(number0_input)+int(number2_input)
output_label2.configure(sum)
elif number == 2:
output_label.configure(text="plus")
number0_ask = tk.Label(master=window, text='input first number')
number0_input = tk.Entry(master=window, width=15)
number2_ask = tk.Label(master=window, text='input second number')
number2_input = tk.Entry(master=window, width=15)
sum = int(number0_input) + int(number2_input)
output_label2.configure(sum)
else:
output_label2.configure("none of our program")
return
window = tk.Tk()
window.title("calulator")
window.minsize(width=400, height=400)
tittle_label = tk.Label(master=window, text="enter order 1 for plus 2 for minus")
tittle_label.pack(pady=20)
number1_input = tk.Entry(master=window, width=15)
number1_input.pack(pady=20)
go_button = tk.Button(master=window, text="result", command=show_output, width=15,
height=2)
go_button.pack(pady=20)
output_label = tk.Label(master=window)
output_label.pack(pady=20)
output_label2 = tk.Label(master=window)
output_label2.pack(pady=20)
window.mainloop()

Categories

Resources