I have used a loop to turn a list of 4 values into a set of buttons. I need to overwrite the text of these buttons to contain the values of another list (in this case Ans2). any help would be greatly appreciated.
import tkinter as tk
root = tk.Tk()
def NextQuestion():
print("this is where i need to configure the buttons to contain values from list - Ans2")
Ans1 = [6,5,32,7]
Ans2 = [4,9,3,75]
AnsNo = 0
r = 0
c = 0
for x in range(len(Ans1)):
AnsBtn = tk.Button(root, text=(Ans1[AnsNo]), command = NextQuestion)
AnsBtn.grid(row=r, column=c)
AnsNo = AnsNo+1
if r == 1:
c = 1
r = 0
else:
r = r+1
First you need to store the buttons somewhere so they can be accessed to be changed. Then you just access their text variable and change it.
import tkinter as tk
root = tk.Tk()
def NextQuestion():
for i, button in enumerate(buttons):
button["text"] = Ans2[i]
Ans1 = [6,5,32,7]
Ans2 = [4,9,3,75]
buttons = []
AnsNo = 0
r = 0
c = 0
for i,answer in enumerate(Ans1):
AnsBtn = tk.Button(root, text=(answer), command = NextQuestion)
AnsBtn.grid(row=r, column=c)
buttons.append(AnsBtn)
if r == 1:
c = 1
r = 0
else:
r = r+1
root.mainloop()
Related
I need to change my keyboard on screen place but I dont know how to do anyone know it? code is :
def click(key):
if key == "<-":
entry2 = entry.get()
pos = entry2.find("")
pos2 = entry2[pos:]
entry.delete(pos2, tk.END)
elif key == " Space ":
entry.insert(tk.END, ' ')
else:
entry.insert(tk.END,key)
button_list = [
'q','w','e','r','t','y','u','i','o','p','<-',
'a','s','d','f','g','h','j','k','l',
'z','x','c','v','b','n','m'
,' Space '
]
r = 2
c = 0
for b in button_list:
rel = 'groove'
command = lambda x=b: click(x)
if b != " Space ":
tk.Button(pencere, text = b, width = 5, relief = rel, command = command).grid(row = r, column = c)
if b == " Space ":
tk.Button(pencere, text = b, width = 30, relief = rel, command = command).grid(row = 10, columnspan = 10)
c+=1
if c > 10 and r == 2:
c = 0
r+=1
if c > 8 and r == 3:
c = 0
r+=1
mainloop()
if anyone want I can send full code but I think you dont need more
Assuming your question is about placing your window on screen.
Solution
You can use the geometry() method to configure geometry of your window.
it takes a string in the format WxH±X±Y.
Reference
Geometry strings
Example
import tkinter as tk
root = tk.Tk()
root.geometry("300x300+100+100")
root.mainloop()
I am making a point of sale systems and one of the important things I'm trying to make is a total button or just a total. So when the total button is pressed, or every time an item is added, the total will be recalculated and outputted.
I started off with just declaring the variables:
item1_qty = 0
item2_qty = 0
item3_qty = 0
item4_qty = 0
item5_qty = 0
item6_qty= 0
item7_qty = 0
item8_qty = 0
item1_price = 0
item2_price = 0
item3_price = 0
item4_price = 0
item5_price = 0
item6_price = 0
item7_price = 0
item8_price = 0
itemTotal=0
and I'm using this code for the actual item buttons (I have 4 currently just so I don't get confused but I've included the first 2)
#Item1 Button + Function
def item1_Button():
global item1_qty
item1_text = ("Chips")
item1_price = "2.00"
item1_qty += 1
item1_text = (item1_text + " "+item1_price +" "+ str(item1_qty)) #concatonates text & variable
item1.config(text=item1_text) #updates label text - doesn't add multiple
item1.place(x=0, y=0) #places label within the frame
item1_Button = Button(itemFrame, text="Chips", width=10, height=10, command=item1_Button)
#creates button + links to function
item1_Button.grid(row=1, column=1) #positions button
item1 = Label(receiptFrame)#creates label for button
#Item2 Button + Function
def item2_Button():
global item2_qty
item2_text = "Fish & Chips"
item2_price = "5.00"
item2_qty += 1
item2_text = (item2_text + " "+item2_price +" "+ str(item2_qty)) #concatonates text & variable
item2.config(text=item2_text) #updates label text - doesn't add multiple
item2.place(x=0, y=50)
item2_Button = Button(itemFrame, text="Fish & Chips", width=10, height=10, command=item2_Button)
item2_Button.grid(row=1, column=2)
item2 = Label(receiptFrame)
I'm not entirely sure what I'm doing in terms of the actual total button, so I have kind of just started off with this:
def updateTotal():
global item1_price, item2_price, item3_price, item4_price
global item1_qty, item2_qty, item3_qty, item4_qty
itemPrice = item1_price + item2_price + item3_price + item4_price
itemQuantity = item1_qty + item2_qty + item3_qty + item4_qty
itemTotal = (itemPrice * itemQuantity)
totalPrice.config(text=str(itemTotal))
totalPrice = Label(totalFrame, font=("arial", 25), text="0"+str(itemTotal))
totalPrice.place(x=10, y=10)
totalButton = Button(totalFrame, text="Total", command=updateTotal, width=15, height=5)
totalButton.place(x=450, y=0)
Is there something I need to do different in terms of how I use the variables?
I would prefer if the total was just text that updated every time an Item button was clicked instead of a Total button but I would appreciate some guidance as nothing is happening at the moment and I'm not entirely sure what I need to do as I'm fairly new with tkinter.
You didnt provide a minimal reproducible example and this post is 2 months old so im not gonna really explain the code and it is mostly self explanatory.
used f-strings, they are like this:
intensifier = input("Enter an intensifier: ")
adjective = input("Enter an adjective: ")
sentence = f"This is {intensifier} {adjective}"
print(sentence)
The curly-brackets let you enter none string values and are automatically turned into a string. (Useable in most scenarios and no concatenation)
Changed items into lists, lists can be used like this:
list1 = ["value1",2,[value3]]
print(list1[0]) #Would print, "value1"
print(list1[1:2])#Would print, [2,[value3]]
Listbox is a box of lists, you can add stuff into it using
listbox.insert(<place to add to>, <object to add>)
Full Code:
from tkinter import *
root = Tk()
root.title("Receipt System")
items_qty = [0,0,0,0]
items_price = [2,5,0,0]
items_text = ["Chips","Fish&chips","",""]
global itemTotal #Global variable
items_total = [0,0,0,0]
currency = "£" #Sets currency
#Functions
def addItem(x):
items_qty[x] += 1 #Adds 1
totalPrice = items_qty[x] * items_price[x] #quantity * price
text = f"{items_qty[x]}x {items_text[x]} {currency}{totalPrice}"
for i in range(0, receipt.size()):
if items_text[x] in receipt.get(i):
receipt.delete(i)
receipt.insert(END, text)
updateTotal(x)
def updateTotal(x):
global items_total
items_total[x] = items_qty[x] * items_price[x] #quantity * price
total = 0
for i in range(0, len(items_total)):
total += items_total[i]
totalPrice.config(text=f"Total: {currency}{str(total)}")
#UI
itemFrame = Frame(root)
itemFrame.pack(pady = 10)
receiptFrame = Frame(root)
receiptFrame.pack(pady = 10)
item1Btn = Button(itemFrame, text=f"Chips - {currency}{items_price[0]}", command=lambda: addItem(0)).pack(side = LEFT, padx = 10)
item2Btn = Button(itemFrame, text=f"Fish & Chips - {currency}{items_price[1]}", command=lambda: addItem(1)).pack(side = LEFT, padx =10)
receipt = Listbox(receiptFrame, selectmode = SINGLE, width = 30) #Receipt list
receipt.pack()
totalPrice = Label(receiptFrame, text = f"Total: {currency}0")
totalPrice.pack(pady = 10)
root.mainloop()
I'm learning to work with Python and Tkinter, so I'm doin this simple calculator app. My main problems come from the function calculator_tasks:
In the first condition, it should be deleting the 0, but it doesn't do it, why is that?
I'm trying to get text when I press the button, but it just prints '/', what's wrong in that?
Please see below the full code, so you might be able to help me.
from tkinter import *
import tkinter as tk
class calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
master.geometry("10x10")
grid_size = 4
a=0
while a <= grid_size:
master.grid_rowconfigure(a,weight=1, uniform='fred')
master.grid_columnconfigure(a,weight=1, uniform='fred')
a += 1
self.ini_frame = Frame(master,bg="light blue",highlightthickness=2, highlightbackground="black")
self.calc_title = Label(self.ini_frame, text ="Calculator",bg="light blue")
self.calculation_frame = Frame(master,bg="black")
self.calculation = IntVar(master,0)
self.calc_figure = Text(self.calculation_frame,fg="white",bg='black')
self.calc_figure.insert(END,0)
self.ini_frame.grid(columnspan=4,sticky=NSEW)
self.calculation_frame.grid(row=1,columnspan=4,sticky=NSEW)
self.calc_title.grid(padx=20)
self.calc_figure.grid(pady=20,padx=20)
master.update_idletasks()
def calculator_tasks():
if self.calc_figure.get("1.0",END) == 0:
self.calc_figure.delete(0,END)
self.calc_figure.insert(END,i)
else:
self.calc_figure.insert(END,i)
r = 2
c = 0
numbers = list(range(10))
numbers.remove(0)
self.calculator_btns=[ ]
for i in numbers:
if c == 2:
self.calculator_btns.append( Button(master, text = i, command = calculator_tasks))
self.calculator_btns[-1].grid(row = r, column = c, pady=20, padx=20,sticky=NSEW)
r += 1
c = 0
else:
self.calculator_btns.append( Button(master, text = i,command=calculator_tasks))
self.calculator_btns[-1].grid(row = r, column = c, pady=20, padx=20,sticky=NSEW)
c += 1
operators = ["+","*","/"]
self.operator_btns =[ ]
r=2
for i in operators:
self.operator_btns.append( Button(master, text = i))
self.operator_btns[-1].grid(row = r, column = 3, pady=20, padx=20,sticky=NSEW)
r += 1
root = Tk()
gui = calculator(root)
root.mainloop()
Here is a simple example:
According to your question: Retrieve text from button created in a loop
import tkinter as tk
root = tk.Tk()
####### Create Button ###############
def get_text(text):
print(text)
for i in range(10):
text = f'Hello I am BeginnerSQL74651 {i}'
button = tk.Button(root, text=text, command=lambda button_text=text: get_text(button_text))
button.grid()
root.mainloop()
I've been making a script for checking grammar. Now I've updated it to be in a gui using Tkinter. The problem is that I'm trying to indicate the row where the grammar is wrong, and when I use an entry field to input the text everything is in one row.
My question is how do you expand the entry field?
This is my code:
import re
from tkinter import *
window = Tk()
window.minsize(width=300, height= 20)
wr = []
def work():
x = e1.get()
print(x)
BigLetterSearcher = re.compile(r'\. .|\n')
mo = BigLetterSearcher.findall(e1.get())
x = 1
y = 0
v = 0
z = ""
wr = []
for i in mo:
if i == '\n':
x += 1
elif i != i.upper():
v = 1
if x != y:
z = "Row", x
wr.append(z)
wr.append(i)
y = x
if v == 0:
wr.append ("Congratulations none of your grammar was wrong!")
l1.configure(text=wr)
l1 = Label(window, text="example")
e1 = Entry(window, text="Enter text here: ")
b1 = Button(window, text="Work", command=work)
leb = [l1, e1, b1]
for all in leb:
all.pack()
window.mainloop()
The entry widget is not capable of being expanded vertically. This is because there is already a widget designed for this and that is called Text(). For adding text to the text widget we can use insert() and you specify where with a 2 part index. The first part is the row and the 2nd is the column. For the row/line it starts at number 1 and for the index of that row it starts at zero.
For example if you wish to insert something at the very first row/column you would do insert("1.0", "some data here").
Here is you code with the use of Text() instead.
import re
from tkinter import *
window = Tk()
window.minsize(width=300, height= 20)
wr = []
def work():
x = e1.get("1.0", "end-1c")
print(x)
BigLetterSearcher = re.compile(r'\. .|\n')
mo = BigLetterSearcher.findall(x)
x = 1
y = 0
v = 0
z = ""
wr = []
for i in mo:
if i == '\n':
x += 1
elif i != i.upper():
v = 1
if x != y:
z = "Row", x
wr.append(z)
wr.append(i)
y = x
if v == 0:
wr.append ("Congratulations none of your grammar was wrong!")
l1.configure(text=wr)
l1 = Label(window, text="example")
e1 = Text(window, width=20, height=3)
e1.insert("end", "Enter text here: ")
b1 = Button(window, text="Work", command=work)
leb = [l1, e1, b1]
for all in leb:
all.pack()
window.mainloop()
Expanding an Entry field vertically can only be done by changing the size of the font associated with the Entry field...
e1 = Entry(window, text="Enter text here: ", font=('Ubuntu', 24))
results in a taller Entry field than
e1 = Entry(window, text="Enter text here: ", font=('Ubuntu', 12))
I have written a code where Label and Entry widgets' variables are put in a list (in order to avoid the number of lines which will take for creation of each Label and Entry widgets). Then a for loop to create Label and Entry widgets are used, A submit button is used which have to list the entries of each Entry widget. But an empty value is displayed instead of displaying the entered value. Can anyone help me to know the reason and correct the code.
Below is the code which I have written:
from Tkinter import *
app = Tk()
list1 = ['l1','l2','l3']
list2 = ['e1','e2','e3']
entries = []
r = 0
c = 0
for m,n in zip(list1, list2):
x = Label(app, text=m)
x.grid(row = r, column =c)
n = StringVar()
e = Entry(app, textvariable = n)
e.grid(row =r , column = c+1)
entries.append(e.get())
r = r + 1
def func():
entries.append("Dfg")
print entries
s = Button(app, text = "Submit", command = func)
s.grid(row = r, columnspan=2)
app.minsize(400, 400)
app.mainloop()
Please note: There could be indentation problem while posting the code, sorry for the inconvenience.
The for loop is for initialize in this case, When the Entry is been created,The input of Entry is empty , so when you entries.append(e.get()) got the empty
.I change something from your code , and the entries will be entered value when you click the button BTW I use python3 instead of python2
from tkinter import *
app = Tk()
list1 = ['l1','l2','l3']
list2 = ['e1','e2','e3']
entries = []
e = []
r = 0
c = 0
for index, m in enumerate(zip(list1, list2)):
x = Label(app, text=m)
x.grid(row = r, column =c)
n = StringVar()
e.append( Entry(app, textvariable = n))
e[index].grid(row =r , column = c+1)
r = r + 1
def func():
entries = []
for a in e:
entries.append(a.get())
print(entries)
s = Button(app, text = "Submit", command = func)
s.grid(row = r, columnspan=2)
app.minsize(400, 400)
app.mainloop()