How can I make a button input as Integer - python-3.x

I just started to work with python with a little to no actual programming background. As most of the newcomers I am writing a calculator. I've got some buttons for writing my numbers into a label. This works well if I set the textvariable in StringVar as the snippet below:
numbers = StringVar()
display = Label(root, font = "Arial 20", textvariable = numbers, relief = RIDGE, anchor = E)
But when I set this into IntVar it doesnt work anymore. I don't seem to be able to solve my problem. Here is some more of my code to clearify what Im doing (wrong?).
numbers = IntVar()
display = Label(root, font = "Arial 20", textvariable = numbers, relief = RIDGE, anchor = E)
display.place(x=1, y=1, width=212,height=47
def display_input (inputValue):
CurrentInput = numbers.get()
numbers.set(CurrentInput + inputValue)
btn1 = Button(root, text = '1', bd = '1', bg = 'lightsteelblue', relief = RAISED, command = lambda: display_input('1'))
btn1.place(x=1, y=96, width=71,height=47)

here you are calling the display_input function with a string (str) instead of an integer (int):
# '1' with quotes is a string, not an integer
Button(root, ..., command = lambda: display_input('1'))
This will make you attempt to update an IntVar with the result of the sum of an int with a str, which is not supported:
>>> 0 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Replacing that command with display_input(1) instead (here 1 is an int) should fix your issue.

Related

what am i doing wrong with tkinter application for email slicer?

making an email slicer,
some errors I'm getting are:
AttributeError: 'bool' object has no attribute 'index'
ValueError: substring not found
now, with this specific code, I'm getting no result at all, it just doesn't do anything when I click the button
root = Tk()
e = Entry(root)
e.grid(row = 6, column = 6)
s = Label(root)
s.grid(row = 1, column = 1)
wel = Label(root, text = "whats your email")
wel.grid(row = 1, column = 5)
inp = Entry(root)
inp.grid(row = 3, column = 5)
def callback(re = inp.get()):
us = re[:re.startswith("#")]
uss = re[re.startswith("#")+1:]
var = StringVar()
var.set(us + uss)
sub = Button(root, text = "submit", command = lambda:callback())
sub.grid(row = 5, column = 5)
final = Label(root, textvariable = var)
final.grid(row = 5, column = 6)
root.mainloop()
You need to
call inp.get() inside callback(), not as default value of argument
use find() instead of startswith()
call var.set(...) inside the function as well
def callback():
re = inp.get()
pos = re.find("#")
if pos >= 0:
user = re[:pos]
domain = re[pos+1:]
var.set(user+","+domain)
else:
var.set("Invalid email")
Note that above is not enough to check whether the input email is valid or not, for example two "#" in the input.

How to make a button Stay where it is when text is changing length

So i Have been trying to make this button stay in the same position but when ever the text changes its length the button always moves
i have tried removing the row and column values that doesn't work
i have tried changing the row and column values that doesn't work
so i don't really know what to do
from tkinter import *
win = Tk()
win.title('ab')
win.config(bg='blue')
win.geometry('200x100')
i = 0
def changetext():
global i
i = i + 1
if i == 1:
lbl.config(text='a')
if i == 2:
lbl.config(text='ab')
if i == 3:
lbl.config(text='abc')
if i == 4:
lbl.config(text='abcd')
if i == 5:
lbl.config(text='abcde')
lbl = Label(win,text='111111111111', font=("Courier", 9))
lbl.grid(row=1,column=2)
btn = Button(win,text='u', command =changetext)
btn.grid(row=2,column=2)
win.mainloop()
When you make the button (or pretty much any widget for that matter), you can define its width.
lbl = Label(win, width= 20, text = '111111111111', font = ("Courier",9))
btn = Button(win, width = 20, text = 'u', command = changetext)

Is there any way to create entries in a for loop with separate variables (for accessing later)?

Just working on a personal project and was wondering if it was possible to create entries in a for loop that have their own variables so they could be accessed later. You can do something similar with radiobuttons:
from tkinter import *
mydict = ["a":1, "b":2]
i = -1
var = IntVar()
for key in mydict.keys():
i += 1
Radiobutton(self, text = key, variable = var, value = i).grid(column = 0, sticky = W)
This will create a radiobutton for each key in a dictionary but they all use the same variable.
Aka something that will turn this:
Label(self, text = "Label 1").grid(column = 0, sticky = W)
Entry(self, textvariable = entryOne).grid(column = 1, sticky = W)
Label(self, text = "").grid()
Label(self, text = "Label 2").grid(column = 0, sticky = W)
Entry(self, textvariable = entryTwo).grid(column = 1, sticky = W)
Label(self, text = "").grid()
into a for loop so it could be used for x times.

How to print the same text multiple times(5 times) in tkinter/GUI?

from tkinter import *
root=Tk()
textbox=Text(root)
textbox.pack()
button1=Button(root, text='Output Name', command=lambda : print('Hello'))
button1.pack()
def redirector(inputStr):
textbox.insert(INSERT, inputStr)
sys.stdout.write = redirector
root.mainloop()
This is my code with out a timer to do it five times.
This seems a little bit like homework, so lets try to get you on the right track over outright providing the code to accomplish this.
You're going to want to create a loop that performs your code a certain number of times. Let's say we just want to output a certain string 5 times. As an example, here's some really simple code:
def testPrint():
print('I am text!')
for i in range(5):
testPrint()
This will create a function called testPrint() that prints text "I am Text!", then run that function 5 times in a loop. If you can apply this to the section of code you need to run 5 times, it should solve the problem you are facing.
This worked for me. It creates a table using the .messagebox module. You can enter your name into the entry label. Then, when you click the button it returns "Hello (name)".
from tkinter import *
from tkinter.messagebox import *
master = Tk()
label1 = Label(master, text = 'Name:', relief = 'groove', width = 19)
entry1 = Entry(master, relief = 'groove', width = 20)
blank1 = Entry(master, relief = 'groove', width = 20)
def show_answer():
a = entry1.get()
b = "Hello",a
blank1.insert(0, b)
button1 = Button(master, text = 'Output Name', relief = 'groove', width = 20, command =show_answer)
#Geometry
label1.grid( row = 1, column = 1, padx = 10 )
entry1.grid( row = 1, column = 2, padx = 10 )
blank1.grid( row = 1, column = 3, padx = 10 )
button1.grid( row = 2, column = 2, columnspan = 2)
#Static Properties
master.title('Hello')

updating tkinter window for text background changes

Trying to show a green or red background in the text field of the answer to the simple addition quizzer.
Currently in PyCHarm complains that:
Entry.grid_configure(background = "red")
TypeError: grid_configure() missing 1 required positional argument: 'self'
0
I can't seem to figure this out. Any help is appreciated.
Here's the code so far:
from tkinter import *
import random
class MainGUI:
def __init__(self):
window = Tk() # Create the window
window.title("Addition Quizzer") # Set the title
#window.width(len(window.title()))
self.number1 = random.randint(0, 9)
self.number2 = random.randint(0, 9)
Label(window, text = "+").grid(row = 2, column = 1, sticky = E)
Label(window, text = "Answer").grid(row = 3, column = 1, sticky = W)
self.firstNumber = StringVar()
Label(window, text = self.number1, justify = RIGHT).grid(row = 1, column = 2)
self.secondNumber = StringVar()
Label(window, text = self.number2, justify = RIGHT).grid(row = 2, column = 2)
self.entry = StringVar()
Entry(window, textvariable = self.entry, justify = CENTER, width = 4, background = "grey").grid(row = 3, column = 2)
Button(window, text = "Answer:", command = self.computeAnswer).grid(row = 4, column = 1, sticky = E)
self.result = StringVar()
Label(window, textvariable = self.result).grid(row = 4, column = 2)
window.mainloop() # Create the event loop
def computeAnswer(self):
self.result.set(format(self.number1 + self.number2))
if self.entry == self.result:
self.displayCorrect()
else:
self.displayIncorrect()
def displayCorrect(self):
# self.correctAnswer = "Correct"
# Label(self.window, text = self.correctAnswer, background = "green", justify = RIGHT).grid(row = 5, column = 2)
Entry.grid_configure(background = "green")
def displayIncorrect(self):
# self.incorrectAnswer = "Incorrect"
# Label(self.window, text = self.incorrectAnswer, background = "red", justify = RIGHT).grid(row = 5, column = 2)
Entry.grid_configure(background = "red")
MainGUI()
If you had read and followed this in the Help Center material, you would have reduced your code to the following, which still gets the same error message.
from tkinter import *
Entry.grid_configure()
The message refers to the fact that Python instance methods require an instance. This is usually done by calling the method on an instance instead of the class. Otherwise, an instance must be given as the first argument. Consider
mylist = []
mylist.append(1)
list.append(mylist, 2)
print(mylist)
# [1, 2]
You need to save a reference to your Entry box. Change
Entry(window, ..., background = "grey").grid(...)
to
self.entry = Entry(window, ..., background = "grey").grid(...)
I do not know if calling .grid_configure(background=color will do what you want.
This will, I am sure.
self.entry['background'] = 'red'

Resources