Printing textbox input to console with tkinter (python3.7) - python

I am making tic tac toe in python using tkinter, and the code all works except for when I try to print which player is the winner, I get the following ouput:
The player who won is:
.!entry
The code I used to print out the winner is this:
print("The player who won is: ", e1_entry)
...
where e1_entry is defined as this:
e1_entry = e1.get()
and e1 is:
e1 = tkinter.Entry(window, textvariable=e1_entry)
How would I make it so that the text taken from the tkinter Entry is printed to the console?
Thanks
Gaurav Bhalla

Here is a working example. You would need to define a function to get the string
import tkinter
def getWinner():
n = entry1.get()
if n == "":
n = "Nobody won"
print(n)
root = tkinter.Tk()
entry1 = tkinter.Entry(root)
entry1.grid(row = 0, column = 0)
root.after(10000, getWinner)
root.mainloop()
This has an Entry widget, and after 10 seconds, will call the function 'getWinner'. If the Entry widget has no text in it, there will be no winner.
Hope this helps!

You should try something like:
window = Tk()
text = StringVar()
e1 = Entry(window, textvariable = text)
e1.pack()
e1_entry = text.get()
print("The player who won is:", e1_entry)

Related

Python Random Math Equation Generator program

I've currently been creating a math equation generator program that will ask you random multiplication questions. I have been having trouble with the if statements where ans == answer will be equal dependent on the user's input (correct answer). However, my program does not see it as equal despite being the same value with example from printing ans and answer which shows they are the same value. I don't know if I am doing something wrong and I would like to know a method of fixing my issue.
Also when I tried to create for and while loops for the generating the equations, it would print them all out at once, is there a way to also make it so that the loop will not print a new random equation until the user gets the answer right?
from tkinter import *
from random import *
import random
import time
import tkinter as tk
import math
import operator
from tkinter import messagebox
#This is for creating the tkinter window and fixing the specified dimensions into place
root = tk.Tk()
root.geometry("900x600")
#This section creates the canvas and its specifications
canvas_width = 900
canvas_height = 500
c = Canvas(root, width=canvas_width, height=canvas_height, bg="pink")
c.pack()
def quitgame():
root.destroy()
class Game_Images:
#Background Image
bg = PhotoImage(file="../Data/sidescroll background flip.gif")
bg = bg.zoom(2)
c.create_image(0,0, anchor=NW, image=bg)
#Insert Image of Enemy
enemy = PhotoImage(file="../Data/monke2.png")
enemy1 = c.create_image(0,260, anchor=NW, image=enemy)
#Insert image of playable character
player = PhotoImage(file="../Data/monke2.png")
player1 = c.create_image(0,325, anchor=NW, image=player)
g = Game_Images()
score = 0
x = 1
def game_start():
global answer, question
int_1 = random.randint(1, 12)
int_2 = random.randint(1, 12)
displayQuestion = "What is "+str(int_1)+ "*" + str(int_2)+"?"
operator = ["*"]
ops = random.choice(operator)
c.create_rectangle(353,0,550,75, fill = "white")
c.create_text(450, 50, font = ("Helvetica", 15), fill="pink", text = displayQuestion)
question = str(int_1) + str(ops) + str(int_2)
answer = int_1 * int_2
def generateQ():
ans = e1.get()
e1.delete(0, END)
if ans == answer:
score += 1
x += 1
print("correct")
print(ans)
print(answer)
else:
print("wrong")
print(ans)
print(answer)
#Buttons show up below the canvas to run commands when pressed
Button(root, text = "Commence Forth",width = 15, command = game_start).place(x=10, y=570)
Button(root, text = "Quit",width = 11, command = quitgame).place(x=800, y=570)
e1 = Entry(root)
e1.pack(padx=30, pady=30)
b=Button(root,text="Enter", width=5, font=("Helvetica", 12), command = generateQ)
b.place(x=550, y=534)
root.mainloop()
Change function generateQ() like this -
def generateQ():
global score,x
ans = e1.get()
e1.delete(0, END)
if int(ans) == int(answer):
score += 1
x += 1
print("correct")
print(ans)
print(answer)
else:
print("wrong")
print(ans)
print(answer)
Use int() so that they are of same data type. And use global score,x because it shows error. You could also write score and x as arguments.

Change (update) text in Python Tkinter widgets

I am trying to update information in tkinter labels and buttons without redrawing entire screens. I'm using Python 3, a Raspberry Pi, and Idle. I have a trivial example of what I am trying to do. I see comments here that suggest I need to learn to manipulate stringvariable or IntVar, etc. but my book is totally unhelpful in that regard. In this example, I would like the number between the buttons to track the value of the number as it changes with button pushes.
##MoreOrLess.01.py
from tkinter import *
global number
number = 5
root = Tk()
root.title("Test Buttons")
def Less():
global number
number -= 1
print ("The number is now ", number)
def More():
global number
number += 1
print("The number is now ", number)
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, text = number).pack(pady = 20)
MakeLabel(number)
Not only do you base yourself in a book, check the official documentation of tkinter. in your case you must create a variable of type IntVar with its set() and get() method, and when you want to link that variable through textvariable.
from tkinter import *
root = Tk()
root.title("Test Buttons")
number = IntVar()
number.set(5)
def Less():
number.set(number.get() - 1)
print ("The number is now ", number.get())
def More():
number.set(number.get() + 1)
print("The number is now ", number.get())
def MakeLabel(number):
textvariable = number
label1 = Label(root, text = "Pick a button please.").pack(pady=10)
btnL = Button(root, text = "More", command = More).pack(side = LEFT)
btnR = Button(root, text = "Less", command = Less).pack(side = RIGHT)
label2 = Label(root, textvariable = number).pack(pady = 20)
MakeLabel(number)
root.mainloop()

Python Tkinter StringVar issues

I am trying to make a simple calculator for a game I play as a random project. I found myself very confused on how to go about doing this; I want the user to enter a number in the textbox and it will multiply that number by 64000 and display it in a label above. But, I cannot find out anywhere how to do this. This is just a small practice thing and im amazed I cannot figure it out. Please help meh! Here is my code:
from Tkinter import *
####The GUI#####
root = Tk()
#Title#
root.wm_title("TMF Coin Calculator")
####The Widgets####
a = StringVar()
b = StringVar()
def multiply_a():
d = (int(a) * 64000)
e = str(d)
b.set(e)
b.trace("w", multiply_a)
#Top Label#
top_label = Label(root, fg="red", text="Type the ammount of Coin Stacks you have.")
top_label.grid(row=0, column=0)
#The Output Label#
output_label = Label(root, textvariable=b, width = 20)
output_label.grid(row = 1, column=0)
#User Entry Box#
user_input_box = Entry(root, textvariable=a, width=30)
user_input_box.grid(row=2, column=0)
root.mainloop()
You need to trace the variable that changes: a. Then you need to define multiply_a() to handle an arbitrary number of arguments with *args (happens to be 3 arguments in this case, but *args is fine here).
Go from:
def multiply_a():
d = (int(a) * 64000)
e = str(d)
b.set(e)
b.trace("w", multiply_a)
to:
def multiply_a(*args):
try:
myvar = int(a.get())
except ValueError:
myvar = 0
b.set(myvar * 64000)
a.trace("w", multiply_a)
This will additionally use 0 if the entered value can't be turned into an int.

tkinter: How to change labels inside the program itself

I was asked to edit my code so I decided to include the entire calculator script
from tkinter import *
global choice
choice = 0
#Program
def calculate(*event):
if choice == 1:
try:
add1 = ccalc1.get()
add2 = ccalc2.get()
except:
no = Label(app, text="You must use a number").grid(row=0, column=0)
answ = add1 + add2
answer = Label(app, text = answ).grid(row=1, column=0)
elif choice == 2:
try:
sub1 = ccalc1.get()
sub2 = ccalc2.get()
except:
no = Label(app, text="You must use a number").grid(row=1, column=0)
answ = sub1 - sub2
answer = Label(app, text = answ).grid(row=1, column=0)
def choice2():
global choice
choice = 2
#End Program
#GUI
#Window Info
calc = Tk()
calc.title("Calculator")
calc.geometry("200x140")
#End Window Info
#Build Window
app = Frame(calc)
app.grid()
ccalc1 = IntVar()
ccalc2 = IntVar()
#Widgets
if choice == 0:
welcome = Label(app, text="Select a choice")
elif choice == 2:
welcome.config(text="Subtraction")
calcbox1 = Entry(app,textvariable=ccalc1)
calcbox2 = Entry(app,textvariable=ccalc2)
submit = Button(app, text="CALCULATE", command = calculate)
welcome.grid(row=0,column=0)
calcbox1.grid(row=2, column=0)
calcbox2.grid(row=3, column=0)
submit.grid(row=4, column=0)
calc.bind('<Return>', calculate)
#End Widgets
#Menu
menu=Menu(calc)
#Operations
filemenu = Menu(menu,tearoff=0)
filemenu.add_command(label="Subtract", command = choice2)
menu.add_cascade(label="Operations",menu=filemenu)
calc.config(menu=menu)
calc.mainloop()
#End GUI
what wrong is that the welcome label text wont change accordingly.
Update: I included the entire calculator code
Any help is appreciated.
It's hard to understand what you expect to happen. For example, look at this code:
#Widgets
if choice == 0:
welcome = Label(app, text="Select a choice")
elif choice == 2:
welcome.config(text="Subtraction")
This code will only ever execute once, and choice will always be zero since that's what you initialize it to. It executes once because it's not in a function and not in a loop, so as python parses the code it will run it and move to the next line. That block of text will never be processed a second time.
If you want the label to change when the user selects a menu item, you'll need to execute that code inside the choice2 function:
def choice2():
global choice
choice = 2
welcome.config(text="Subtraction")

Creating a Tkinter math Quiz

I am learning python and am having trouble getting this program to work correctly.
from Tkinter import*
import time
import tkMessageBox
import random
def Questions():
number1 = random.randrange(1,25,1)
number2 = random.randrange(1,50,2)
answer = number1 + number2
prompt = ("Add " + str(number1) + " and " + str(number2))
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
return answer
def start():
global count_flag
Questions()
count_flag = True
count = 0.0
while True:
if count_flag == False:
break
# put the count value into the label
label['text'] = str(count)
# wait for 0.1 seconds
time.sleep(0.1)
# needed with time.sleep()
root.update()
# increase count
count += 0.1
def Submit(answer, entryWidget):
""" Display the Entry text value. """
global count_flag
count_flag = False
print answer
if entryWidget.get().strip() == "":
tkMessageBox.showerror("Tkinter Entry Widget", "Please enter a number.")
if int(answer) != entryWidget.get().strip():
tkMessageBox.showinfo("Answer", "INCORRECT!")
else:
tkMessageBox.showinfo("Answer", "CORRECT!")
# create a Tkinter window
root = Tk()
root.title("Math Quiz")
root["padx"] = 40
root["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Answer:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
#directions
directions = ('Click start to begin. You will be asked a series of questions like the one below.')
instructions = Label(root, text=directions, width=len(directions), bg='orange')
instructions.pack()
# this will be a global flag
count_flag = True
answer = Questions()
Sub = lambda: Submit(answer, entryWidget)
# create needed widgets
label = Label(root, text='0.0')
btn_submit = Button(root, text="Submit", command = Sub)
btn_start = Button(root, text="Start", command = start)
btn_submit.pack()
btn_start.pack()
label.pack()
# start the event loop
root.mainloop()
It just says "INCORRECT!" every time I push submit regardless of what I enter into the text box. Any suggestions would be appreciated. Thanks, Scott
Left side is an integer, right side is a string, so it's always False:
int(answer) != entryWidget.get().strip()
You can try:
int(answer) != int(entryWidget.get().strip())

Categories