As the title suggests, I'm trying to make a counter with IntVar(),so I've tried this.
from tkinter import *
def main():
root = Tk()
root.resizable(FALSE, FALSE)
root.geometry('200x50')
root.title('Home')
#starts here
var = IntVar()
text = 'Count: ' + str(var.get())
b1 = Button(root, text='Test', command=fun)
b1.pack()
l1 = Label(root, text=text)
l1.pack()
mainloop()
def fun():
for i in range(1, 11):
print('test')
main()
But I got confused, I want to make it count the printings and show the value in the label.
Any help would be appreciated.
If you are trying to count the number of times 'test' is printed, you can update the l1 widget with l1['text'] = var after updating. To update, you can fetch the variable of intvar and then add 1 to it. Here's some code:
from tkinter import *
def main():
root = Tk()
root.resizable(FALSE, FALSE)
root.geometry('200x50')
root.title('Home')
#starts here
var = IntVar()
text = 'Count: ' + str(var.get())
b1 = Button(root, text='Test', command=lambda: fun(l1, var))
b1.pack()
l1 = Label(root, text=text)
l1.pack()
mainloop()
def fun(l1, var):
for i in range(1, 11):
print('test')
var.set(var.get()+1)
l1['text'] = 'Count: ' + str(var.get())
main()
Related
I am trying to make a simple calculator, I am using an entry widget to display the numbers, and buttons to type the numbers.
When I type numbers using the buttons, (btn1, btnadd, btn2), it should be like this in the entry widget 1+2 instead it is like this 2+1
I know mathematically they are the same, but it won't be the case with division or subtraction
My code:
from tkinter import *
root = Tk()
def add():
entered.insert(0, '+')
def num_1():
entered.insert(0, 1)
def num_2():
entered.insert(0, 2)
entered = Entry(root)
entered.pack()
btn1 = Button(root, text='1', command=num_1).pack()
btn2 = Button(root, text='2', command=num_2).pack()
btn_add = Button(root, text='+', command=add).pack()
root.mainloop()
P.S I tried using pyautogui write function but the code was lagging and slow.
I'm new, hope this will help you!! ^^ Also, this is "smallest to change" solution: you just need to replace a few characters.
from tkinter import *
root = Tk()
def add():
entered.insert(END, '+') # END instead of 0, it adds '+' at the end
def num_1():
entered.insert(END, 1) # END instead of 0, it adds 1 at the end
def num_2():
entered.insert(END, 2) # END instead of 0, it adds 2 at the end
entered = Entry(root)
entered.pack()
btn1 = Button(root, text='1', command=num_1).pack()
btn2 = Button(root, text='2', command=num_2).pack()
btn_add = Button(root, text='+', command=add).pack()
root.mainloop()
Thank you for making a fun to answer question! :D
So the problem was that entered.insert(0, '+') the 0 is where its going to place the + so every time you were pushing the button you were placing the 1 and the 2 and the + at position 0
from tkinter import *
root = Tk()
i= 0
def add():
global i
entered.insert(i, '+')
i += 1
def num_1():
global i
entered.insert(i, 1)
i += 1
def num_2():
global i
entered.insert(i, 2)
i += 1
entered = Entry(root)
entered.pack()
btn1 = Button(root, text='1', command=num_1).pack()
btn2 = Button(root, text='2', command=num_2).pack()
btn_add = Button(root, text=' +', command=add).pack()
root.mainloop()
so now you have the global i that will change the position of the placement...
Ok this is how to delete
from asyncio.windows_events import NULL
from os import remove
from tkinter import *
root = Tk()
i= 0
def add():
global i
entered.insert(i, '+')
i += 1
def num_1():
global i
entered.insert(i, 1)
i += 1
def num_2():
global i
entered.insert(i, 2)
i += 1
def delete():
global i
i -= 1
entered.delete(i)
entered = Entry(root)
entered.pack()
btn1 = Button(root, text='1', command=num_1).pack()
btn2 = Button(root, text='2', command=num_2).pack()
btn_add = Button(root, text=' +', command=add).pack()
btn_rem = Button(root,text ='del', command=delete).pack()
root.mainloop()
I want to get a variable from a function to use this variable in another function.
Simple example:
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text = intro + name
def printresult():
print(text)
root = Tk()
root.title("Test")
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()
If I press the testbutton and afterwards the printbutton, then I get the error "name 'text' is not defined".
So how am I able to get the text variable from the def test() to use it in the def printresult()?
You need to save the value somewhere well known:
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text = intro + name
test.text = text # save the variable on the function itself
def printresult():
print(test.text)
root = Tk()
root.title("Test")
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()
Since you are using tkinter, I'd use a StringVar to store the result. Using a string var makes it easy for other tkinter widgets to use the value.
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text.set(intro + name)
def printresult():
print(text.get())
root = Tk()
root.title("Test")
text = StringVar()
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()
I have a off delay program in which when I select the input checkbutton, the output is 1. When I deselect the input checkbutton, the output goes back to 0 after a timer (set up in a scale). For that I use the after method. That part works. My problem is that I want to reset the timer if the checkbutton is selected again before the output went to 0; but once the checkbutton is selected the first time, the after method get triggered and it doesn't stop. I'm trying to use after_cancel, but I can't get it to work. Any solution?
from tkinter import *
root = Tk()
t1= IntVar()
out = Label(root, text="0")
remain_time = IntVar()
grab_time = 1000
def start_timer(set_time):
global grab_time
grab_time = int(set_time) * 1000
def play():
if t1.get() == 1:
button1.configure(bg='red')
out.configure(bg="red", text="1")
else:
button1.configure(bg='green')
def result():
out.configure(bg="green", text="0")
out.after(grab_time,result)
button1 = Checkbutton(root,variable=t1, textvariable=t1, command=play)
time = Scale(root, from_=1, to=10, command=start_timer)
button1.pack()
time.pack()
out.pack()
root.mainloop()
Expected: when press the checkbutton before the output went to 0, reset the counter.
So you could use the .after_cencel when the value of checkbutton is 1:
from tkinter import *
root = Tk()
t1= IntVar()
out = Label(root, text="0")
remain_time = IntVar()
grab_time = 1000
def start_timer(set_time):
global grab_time
grab_time = int(set_time) * 1000
def play():
if t1.get() == 1:
button1.configure(bg='red')
out.configure(bg="red", text="1")
try: # when the first time you start the counter, root.counter didn't exist, use a try..except to catch it.
root.after_cancel(root.counter)
except :
pass
else:
button1.configure(bg='green')
def result():
out.configure(bg="green", text="0")
root.counter = out.after(grab_time,result)
button1 = Checkbutton(root,variable=t1, textvariable=t1, command=play)
time = Scale(root, from_=1, to=10, command=start_timer)
button1.pack()
time.pack()
out.pack()
root.mainloop()
So I am writing a Python program in class that uses the Caesar cipher to take a users input and output it as cipher-text. Since i had a lot more time for this project I planned on giving it a GUI in Tkinter. But when I assign the resulted cipher-text to a label it won't display it and keeps it blank. I'm a noob to python and even more to Tkinter so I'm not too keen on being able to fix these issues myself. Here's the code:
import string
import collections
import random
import tkinter
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("Encoder")
root.geometry("500x400")
def caesar(rotate_string, number_to_rotate_by):
upper = collections.deque(string.ascii_uppercase)
lower = collections.deque(string.ascii_lowercase)
upper.rotate(number_to_rotate_by)
lower.rotate(number_to_rotate_by)
upper = ''.join(list(upper))
lower = ''.join(list(lower))
return rotate_string.translate(str.maketrans(string.ascii_uppercase, upper)).translate(str.maketrans(string.ascii_lowercase, lower))
def callback():
print (code)
b = Button(root, text="get", width=10, command=callback)
b.pack()
var = StringVar()
e = Entry(root, textvariable = var)
e.pack()
our_string = e.get()
random_number = random.randint(1,25)
code = caesar(our_string, random_number)
l = Label(root, textvariable=code, anchor=NW, justify=LEFT, wraplength=398)
l.pack()
l.place(relx=0.5, rely=0.5, anchor=CENTER)
root.mainloop()
There are several issues with the code you've posted. First and foremost, your callback doesn't do anything besides print the code variable. You need to move your call to caesar and the associated code into the callback, like so
def callback():
global code
our_string = e.get()
random_number = random.randint(1, 25)
code.set(caesar(our_string, random_number))
The second issue that I see is that you need to use a StringVar as the textvariable argument in your Label constructor in order to get the label to update automatically. When all is said and done, my version of your code looks like
import string
import collections
import random
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("Encoder")
root.geometry("500x400")
code = StringVar()
code.set('Hello')
def caesar(rotate_string, number_to_rotate_by):
upper = collections.deque(string.ascii_uppercase)
lower = collections.deque(string.ascii_lowercase)
upper.rotate(number_to_rotate_by)
lower.rotate(number_to_rotate_by)
upper = ''.join(list(upper))
lower = ''.join(list(lower))
return rotate_string.translate(str.maketrans(string.ascii_uppercase, upper)).translate(str.maketrans(string.ascii_lowercase, lower))
def callback():
global code
our_string = e.get()
random_number = random.randint(1, 25)
code.set(caesar(our_string, random_number))
b = Button(root, text="get", width=10, command=callback)
b.pack()
var = StringVar()
e = Entry(root, textvariable=var)
e.pack()
l = Label(root, textvariable=code, anchor=NW, justify=LEFT, wraplength=398)
l.pack()
l.place(relx=0.5, rely=0.5, anchor=CENTER)
root.mainloop()
This seems to do what you'd expect.
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.