I'm trying to make a GUI version of a drinking game, which involves throwing dice. I 'throw the dice' virtually, but want to display the outcome on the screen. I thought using Label() would be most useful, but i'm having trouble updating that text (the throw_text variable) when a new dice throw is done.
Instead of the text updating on the screen, a new text appears below the previous one with the new throw.
I don't want a cascading stream of text, but just one singular text that updates at the dice being thrown i.e. when the 'Roll!' button is pressed.
I've seen people do it using the Stringvar(), however i must be doing it wrong as it does not have an effect on the appearance.
from tkinter import *
dim = [900, 600]
root = Tk()
root.geometry(f"{dim[0]}x{dim[1]}")
root.title("Mex")
root.iconbitmap("dice.ico")
lbl = Label(root, font=("Times", 200))
num = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685']
d1 = None
d2 = None
throw_txt = StringVar()
def roll_dice():
global d1, d2
d1 = random.choice(num)
d2 = random.choice(num)
lbl.config(text=f"{d1}{d2}")
lbl.pack()
lbl.place(x=dim[0] / 3.8, y=50)
print("Throw:", check_throw(convert_symbol()))
throw_txt = str(check_throw(convert_symbol()))
txt = Label(root, text=throw_txt)
txt.pack(side=TOP)
def convert_symbol():
d1_num = None
d2_num = None
for n in num:
if n == d1:
d1_num = num.index(n) + 1
if n == d2:
d2_num = num.index(n) + 1
if d2_num > d1_num:
throw = f"{d2_num}{d1_num}"
else:
throw = f"{d1_num}{d2_num}"
return throw
def check_throw(t):
num_t = int(t)
if num_t == 21:
return "Mex"
elif num_t % 11 == 0:
return f"Koning: {int(num_t / 11 * 100)}"
elif num_t % 31 == 0:
return "Slok uitdelen"
else:
return str(num_t)
roll_btn = Button(root, text="Roll!", width=10, command=roll_dice)
roll_btn.config(font=("Bahnschrift", 20))
roll_btn.pack()
roll_btn.place(x=dim[0] / 2.5, y=25)
roll_btn = Button(root, text="Convert", width=10, command=convert_symbol)
roll_btn.config(font=("Bahnschrift", 20))
roll_btn.pack()
roll_btn.place(x=dim[0] / 2.5, y=500)
root.mainloop()
You could use the configure attribute instead of storing the text of the Label widget into a separate variable.
Take a quick look at this code:
from tkinter import *
root = Tk()
root.title("my game")
def change_text():
mylabel.configure(text="You just hit the button!")
mylabel = Label(root, text="Hit the button pls")
mylabel.grid(column=0, row=1, sticky='w')
mybutton = Button(root, text="Click me", command=change_text)
mybutton.grid(column=0, row=2, sticky='w')
root.mainloop()
Related
import tkinter as tk
Hoogte = 900
breedte = 1440
def doelwitpress(argumenten):
if argumenten == 1:
input("1")
if argumenten == 2:
input("2")
if argumenten == 3:
input("3")
import random
print('Kies uit 1 (kleinst), 2 (kleiner) of 3 (grootsts):')
willekeurigwoord = input()
kleinstedoelwit = ['beneficial', 'eloquent', 'in proximity']
x = random.choice(kleinstedoelwit)
if (willekeurigwoord == 1):
print(x)
kleineredoelwit = ['useful', 'advise', 'commence']
y = random.choice(kleineredoelwit)
if (willekeurigwoord == "2"):
print(y)
grootstedoelwit = ['vehicle', 'combined', 'uproar']
z = random.choice(grootstedoelwit)
if (willekeurigwoord == "3"):
print(z)
root = tk.Tk()
GrafischeUIcanvas = tk.Canvas(root, height=Hoogte)
GrafischeUIcanvas = tk.Canvas(root, width=breedte)
GrafischeUIcanvas.pack()
achtergrondkleur = tk.Frame(root, bg='#6BAB55')
achtergrondkleur.place(relwidt=1, relheight=1)
kleinstedoelwit = tk.Button(root, text="kleinste doelwit", command=lambda: doelwitpress(1))
kleineredoelwit = tk.Button(root, text="kleinere doelwit", command=lambda: doelwitpress(2))
grootstedoelwit = tk.Button(root, text="grootste doelwit", command=lambda: doelwitpress(3))
kleinstedoelwit.pack(side="left")
kleineredoelwit.pack(side="bottom")
grootstedoelwit.pack(side="right")
root.mainloop()
when i only run my code without gui i can get a word out but i have to manually type it in. I want my tkinter button to be my input and get an output from my code. I basically want to press a button in the UI, the UI then inputs a number and that number equals to one of the lists whith random words. The only thing that happens right now is that it shows the input of my press and then it crashes after 1 input. It doesnt even display 1 random chosen word.
Im using tkinter and random.choice
You should be using Entry widget to get the input from the user and Label or a messagebox to display output.
I have rewritten your code, without changing any logic. (Note: This is only for demonstration purposes as I have no idea how your GUI should come together. It's up to you to make further changes)
In the below code, I have set entry and entry2 to a variable var and var1 respectively. You can use this variable to get and set the value in the Entry widget as shown in the below code.
For output, I have used a label. You may change the text by using label.config(text='abc') or label.configure(text='abc') or just by accessing the text like lable[text] = 'abc'
import tkinter as tk
import random
Hoogte = 900
breedte = 1440
def doelwitpress(argumenten):
if argumenten == 1:
var.set('1')
if argumenten == 2:
var.set('2')
if argumenten == 3:
var.set('3')
lbl['text'] = 'Kies uit 1 (kleinst), 2 (kleiner) of 3 (grootsts):'
#print('Kies uit 1 (kleinst), 2 (kleiner) of 3 (grootsts):')
#willekeurigwoord = input()
kleinstedoelwit = ['beneficial', 'eloquent', 'in proximity']
x = random.choice(kleinstedoelwit)
if (var2.get() == '1'):
lbl['text'] = x
#print(x)
kleineredoelwit = ['useful', 'advise', 'commence']
y = random.choice(kleineredoelwit)
if (var2.get() == "2"):
lbl['text'] = y
#print(y)
grootstedoelwit = ['vehicle', 'combined', 'uproar']
z = random.choice(grootstedoelwit)
if (var2.get() == "3"):
lbl['text'] = z
#print(z)
root = tk.Tk()
var = tk.StringVar()
var2 = tk.StringVar()
GrafischeUIcanvas = tk.Canvas(root, height=Hoogte)
GrafischeUIcanvas = tk.Canvas(root, width=breedte)
GrafischeUIcanvas.pack()
achtergrondkleur = tk.Frame(root, bg='#6BAB55')
achtergrondkleur.place(relwidt=1, relheight=1)
#achtergrondkleur.pack()
kleinstedoelwit = tk.Button(root, text="kleinste doelwit", command=lambda: doelwitpress(1))
kleineredoelwit = tk.Button(root, text="kleinere doelwit", command=lambda: doelwitpress(2))
grootstedoelwit = tk.Button(root, text="grootste doelwit", command=lambda: doelwitpress(3))
kleinstedoelwit.pack(side="left")
kleineredoelwit.pack(side="bottom")
grootstedoelwit.pack(side="right")
lbl = tk.Label(root, bg='#6BAB55', fg='red')
lbl.pack()
entry = tk.Entry(root, textvariable=var)
entry.pack()
entry2 = tk.Entry(root, textvariable=var2)
entry2.pack()
root.mainloop()
I have a Python file that when run, opens a window for simple addition practice. It asks the user for their input, and if the total is correct will output "Right!" and "Oops!" for incorrect. Below all of this is a counter that keeps track of the correct number out of the total. However, at the moment, those numbers both remain zero when user enters their input. What kind of changes would need to be made under the ClicktheButton1 function in order to get this program properly functioning? Thanks.
The output would end up looking like "2 out 4 correct" in the window, updating after each new problem is solved.
from tkinter import *
import random as rn
window = Tk()
window.geometry('350x350')
window.title("C200")
x = rn.randint(0,100)
y = rn.randint(0,100)
correct, incorrect = 0,0
myLabel = Label(window, text="{0}+{1}=".format(x,y), font=("Arial Bold", 15))
myLabel.grid(column=0, row=0)
myLable2 = Label(window, text = "",font=("Arial Bold", 15))
myLable2.grid(column=0, row=5)
mylabel3 = Label(window,text = "0 out of 0 correct",font=("Arial Bold", 15))
mylabel3.grid(column=0, row=10)
mytxt = Entry(window, width=12)
mytxt.grid(column=1,row=0)
def ClicktheButton1():
global x
global y
global correct
global incorrect
myguess = int(mytxt.get())
if x + y == myguess:
myLable2.configure(text = "Right!")
correct += 1
else:
myLable2.configure(text = "Oops!")
incorrect += 1
x = rn.randint(0,100)
y = rn.randint(0,100)
mytxt.focus()
mytxt.delete(0,END)
myLabel.configure(text = "{0}+{1}=".format(x,y))
btn1 = Button(window, text="check", command = ClicktheButton1)
btn1.grid(column=0, row=7)
def ClicktheButton2():
window.destroy()
btn1 = Button(window, text="Quit", command = ClicktheButton2)
btn1.grid(column=400, row=400)
window.mainloop()
You have to change text in mylabel3 in the same why as you change text in myLabel - and even in the same place. I don't know why you have problem with this.
myLabel.configure(text = "{0}+{1}=".format(x,y))
mylabel3.configure(text="{0} of {1} correct".format(correct, correct+incorrect))
I have this code and basically what I want to do is I want that on pressing the button the balance at the button is updated with the amount. If the balance is currently 15, and I add 10, I want it to add 10 to it.
from tkinter import *
def bal():
ans = int (input1.get ())
total = IntVar ()
tot = int (total.get ())
tot = tot + ans
res.set(tot+ans)
root = Tk()
root.geometry("1280x720")
upper = Frame(root)
upper.pack()
Label(upper, text ="Sum:", font = ('raleway', 15), ).grid(row=0, column = 0)
Label(root, text ="Balance:", font = ('raleway', 15)).place(rely=1.0, relx=0, x=0, y=0, anchor=SW)
res = StringVar()
input1 = Entry(upper)
num2 = Entry(root)
result = Label(root, textvariable = res,font = ('raleway',13))
result.place(rely=1.0, relx=0, x=80, y=-2, anchor=SW)
input1.grid(row=0,column=2)
Button(upper, text ="Add Funds", command = bal).grid(row=4, column=2, ipadx = 65)
mainloop()
root.mainloop()
I tried to have a total that constantly updates in the function bal but it doesn't update for some reason. I am a python beginner, by the way :D
Thanks for your help!
In the bal() command function, all you need to do is retrieve the current input value and running total (balance), add them together, and then update the running total:
from tkinter import *
def bal():
ans = input1.get()
ans = int(ans) if ans else 0
tot = int(res.get())
tot = tot + ans
res.set(tot)
root = Tk()
root.geometry("1280x720")
upper = Frame(root)
upper.pack()
Label(upper, text="Sum:", font=('raleway', 15)).grid(row=0, column=0)
Label(root, text="Balance:", font=('raleway', 15)).place(rely=1.0, relx=0,
x=0, y=0, anchor=SW)
res = StringVar()
res.set(0) # initialize to zero
input1 = Entry(upper)
result = Label(root, textvariable=res, font=('raleway', 13))
result.place(rely=1.0, relx=0, x=80, y=-2, anchor=SW)
input1.grid(row=0,column=2)
Button(upper, text="Add Funds", command=bal).grid(row=4, column=2, ipadx=65)
root.mainloop()
You created a new IntVar and you are using .get on this. Instead you want to be use get on num2 to get the current number that is stored in there adding the input to this and updating the var.
from tkinter import *
root = Tk()
root.title("Tip & Bill Calculator")
totaltxt = Label(root, text="Total", font=("Helvitca", 16))
tiptxt = Label(root, text="Tip (%)", font=("Helvitca", 16))
peopletxt = Label(root, text="people", font=("Helvitca", 16))
totaltxt.grid(row=0, sticky=E)
tiptxt.grid(row=1, sticky=E)
peopletxt.grid(row=2, sticky=E)
totalentry = Entry(root)
tipentry = Entry(root)
peopleentry = Entry(root)
totalentry.grid(row=0, column=2)
tipentry.grid(row=1, column=2)
peopleentry.grid(row=2, column=2)
ans = Label(root, text = "ANS")
ans.grid(row=4)
def answer(event):
data1 = totalentry.get()
data2 = tipentry.get()
data3 = peopleentry.get()
if tipentry.get() == 0:
ans.configure(str((data1/data3)), text="per person")
return
elif data1 == 0:
ans.configure(text="Specify the total")
return
elif data3 == 0 or data3 ==1:
ans.configure(str(data1*(data2/100+1)))
return
elif data1 == 0 and data2 == 0 and data3 ==0:
ans.configure(text = "Specify the values")
return
else:
ans.configure(str((data1*(data2/100+1)/data3)), text="per person")
return
bf = Frame(root)
bf.grid(row=3, columnspan=3)
calc = Button(bf, text ="Calculate", fg = "black", command = answer)
calc.bind("<Button-1>", answer)
calc.grid(row=3, column=2)
root.mainloop()
I'm trying to make a tip and bill calculator with a simple design just to learn and experiment. However, I encountered a horrible problem that kept haunting for days, I usually struggle with functions in python and I'm trying to bind a function to a calculate button, which I managed to make it appear. However, I can't manage to get it to work. After some messing around I ended with this error, when I click the calculate button.
This is the error after I click the calculate button:
TypeError: answer() missing 1 required positional argument: 'event'
Commands bound to a button do not get an argument, as the nature of the event is already known. Delete 'event'.
You also bind the answer function to an event. The result is that answer is called both without and with an event argument. Get rid of the bind call.
Follow hint given by Bryan. Stop passing a digit string to .configure as a positional parameter. tk will try to interpret is as dictionary. Instead, add the number string to the rest of the label string.
Like rows, columns start from 0.
The frame is not needed.
The following revision works.
from tkinter import *
root = Tk()
root.title("Tip & Bill Calculator")
totaltxt = Label(root, text="Total", font=("Helvitca", 16))
tiptxt = Label(root, text="Tip (%)", font=("Helvitca", 16))
peopletxt = Label(root, text="people", font=("Helvitca", 16))
totaltxt.grid(row=0, column=0, sticky=E)
tiptxt.grid(row=1, column=0, sticky=E)
peopletxt.grid(row=2, column=0, sticky=E)
totalentry = Entry(root)
tipentry = Entry(root)
peopleentry = Entry(root)
totalentry.grid(row=0, column=1)
tipentry.grid(row=1, column=1)
peopleentry.grid(row=2, column=1)
ans = Label(root, text = "ANS")
ans.grid(row=4, column=0, columnspan=2, sticky=W)
def answer():
total = totalentry.get()
tip = tipentry.get()
people = peopleentry.get()
if not (total and tip):
ans['text'] = 'Enter total and tip as non-0 numbers'
else:
total = float(total)
tip = float(tip) / 100
people = int(people) if people else 1
ans['text'] = str(round(total * tip / people, 2)) + " per person"
calc = Button(root, text ="Calculate", fg = "black", command = answer)
calc.grid(row=3, column=1)
root.mainloop()
import sys
from tkinter import *
def main():
mtext = ment.get()
mlabel2 = Label(top, text=mtext).pack()
def isbn():
digits = [(11 - i) * num for i, num in enumerate(map(int, list()))]
digit_11 = 11 - (sum(digits) % 11)
if digit_11 == 10:
digit_11 = 'X'
digits.append(digit_11)
isbn_number = "".join(map(str, digits))
label2 = Label(top, text = "Your ISBN number is",).pack()
top = Tk()
top.geometry("450x450+500+300")
top.title("Test")
button = Button(top,text="OK", command = isbn, fg = "red", bg="blue").pack()
label = Label(top, text = "Please enter the 10 digit number").pack()
ment= IntVar()
mEntry = Entry(top,textvariable=ment).pack()
Hello, I the code at the moment is a working stage, I just need a way of the results printing because at the moment it is not. I would also like the converter to work proper ally with 10 digits and the 11th digit being the number that the converter finds outs. Thanls
Note how the button's command calls the function to perform your operation:
from tkinter import *
def find_isbn(isbn, lbl):
if len(isbn) == 10:
mult = 11
total = 0
for i in range(len(isbn)):
total += int(isbn[i]) * mult
mult -= 1
digit_11 = 11 - (total % 11)
if digit_11 == 10:
digit_11 = 'X'
isbn += str(digit_11)
lbl.config(text=isbn)
top = Tk()
top.geometry("450x450+500+300")
top.title("Test")
button = Button(top, text="OK", command=lambda: find_isbn(mEntry.get(), mlabel2), fg="red", bg="blue")
button.pack()
label = Label(top, text="Please enter the 10 digit number")
label.pack()
mEntry = Entry(top)
mEntry.pack()
mlabel2 = Label(top, text='')
mlabel2.pack()
top.mainloop()
You also need to call .mainloop(), on your master widget to get the whole things started. It's also better to call .pack() on an object on a separate line. pack() and grid() return nothing so you won't be able to use other methods on the object once you do that.