Hi wanted to get in this program something like getting button id, here is code:
import tkinter as tk
root = tk.Tk()
def button_click(event):
button = event.widget
print(button['text'])
buttons = []
k = 0
for x in range(10):
for y in range(10):
buttons.append(tk.Button(root, width=4, height=2, text=k))
buttons[k].grid(row=x, column=y)
buttons[k].bind('<Button-1>', lambda e: button_click(e))
k += 1
root.mainloop()
I want to get extacly same result as that program but without putting any text on those buttons.
Try this
import tkinter as tk
root = tk.Tk()
def button_click(event, btnId):
print(btnId)
buttons = []
k = 0
for x in range(10):
for y in range(10):
buttons.append(tk.Button(root, width=4, height=2))
buttons[k].grid(row=x, column=y)
buttons[k].bind('<Button-1>', lambda e, btnId=k: button_click(e, btnId))
k += 1
root.mainloop()
Don't use text=k instead add a parameter in button_click and pass k as a parameter.
Related
I made 100 buttons and I want to change color of button which pushed.
How can I do that?
Here is my code.
import tkinter as tk
def settingships():
column = -1
row = 0
root = tk.Tk()
root.title('set ships')
root.geometry('470x310')
for i in range(101):
if i > 0:
if i%10 == 1:
row += 1
column = -1
column += 1
text=f'{i}'
btn = tk.Button(root,text=text,command=collback(i)).grid(column=column,row=row)
root.mainloop()
def collback(i):
def nothing():
btn.config(bg='#008000')
return nothing
First, i is not used in collback(). Second btn is undefined in nothing(). You should pass btn to collback() instead.
In order to do that you need to replace the following line:
btn = tk.Button(root,text=text,command=collback(i)).grid(column=column,row=row)
to:
btn = tk.Button(root, text=text)
btn.grid(column=column, row=row)
btn.config(command=collback(btn))
And modify collback() as below:
def collback(btn):
def nothing():
btn.config(bg='#008000')
return nothing
Or simply use lambda to replace collback():
btn.config(command=lambda b=btn: b.config(bg='#008000'))
I am attempting to work with Tkinter, and the mouse events should change the text of the button clicked.
Through testing, this works with right click () and middle click (). However, (left click) uses a function, which should find the "coordinates" of the widget in the array (I need these numbers for later calculations). The bottom row of the grid works, but any other button leads to the bottom-right button being selected.
from tkinter import *
from random import *
win = Tk()
win.geometry("380x410")
win.grid()
buttons = []
def search(event):
for j in range(10):
for i in range(10):
#print(event.widget)
if buttons[j][i] == event.widget:
break
print(i,j)
buttons[j][i].config(text="1")
for y in range(10):
temp = []
for x in range(10):
button = Button(win,text="",width=4,height=2)
button.grid(row=y,column=x)
button.bind("<Button-1>",search)
button.bind("<Button-2>",lambda event: event.widget.config(text=""))
button.bind("<Button-3>",lambda event: event.widget.config(text="R"))
temp.append(button)
buttons.append(temp)
I have tried messing about with lambdas, but I believe the problem lies within the function.
Any help would be appreciated.
Question: Finding widgets in an array Tkinter
Simpler solution
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
for y in range(10):
for x in range(10):
button = tk.Button(self, text="", width=4, height=2)
button._coords = x, y
button.grid(row=y, column=x)
button.bind("<Button-1>", self.on_button_1_click)
def on_button_1_click(self, event):
print('on_button_1_click:{}'.format(event.widget._coords))
if __name__ == '__main__':
App().mainloop()
Maybe this is somewhat close to what you're looking for:
from tkinter import *
from random import *
win = Tk()
win.geometry("380x410")
win.grid()
buttons = []
def search(event):
i2 = 0
j2 = 0
for j in range(10):
for i in range(10):
#print(event.widget)
if buttons[j][i] == event.widget:
i2 = i
j2 = j
event.widget.config(text="1")
break
print(i2,j2)
#buttons[j][i].config(text="1")
for y in range(10):
temp = []
for x in range(10):
button = Button(win,text="",width=4,height=2)
button.grid(row=y,column=x)
button.bind("<Button-1>", lambda event: search(event))
button.bind("<Button-2>",lambda event: event.widget.config(text=""))
button.bind("<Button-3>",lambda event: event.widget.config(text="R"))
temp.append(button)
buttons.append(temp)
win.mainloop()
Are you sure you need coordinates or just the index of the Button in the buttons list?
If you just need to accurately interact with each button try using the index value in a lambda.
from tkinter import *
win = Tk()
win.geometry("380x410")
buttons = []
def search(btn, ndex):
if btn == '1':
buttons[ndex].config(text='1')
if btn == '2':
buttons[ndex].config(text='')
if btn == '3':
buttons[ndex].config(text='R')
for y in range(10):
for x in range(10):
buttons.append(Button(win, text="", width=4, height=2))
ndex = len(buttons) - 1
buttons[-1].bind("<Button-1>", lambda e, z=ndex: search('1', z))
buttons[-1].bind("<Button-2>", lambda e, z=ndex: search('2', z))
buttons[-1].bind("<Button-3>", lambda e, z=ndex: search('3', z))
buttons[-1].grid(row=y, column=x)
win.mainloop()
from the List of radio button I want to know which one was clicked
Whenever a radio button (In python Tkinter) is clicked its returning 0...
I tried the following method:
declaring the 'var' variable global
passing var variable in all function
But none of the steps are working
def get_date(var):
path_read = E1.get()
date_list = readunparseddata.getdate_unparseddate(path_read)
show_date(date_list,var)
def show_date(list_date,var):
print(var)
frame = Tk()
#v.set(1)
Label(frame,text="""Choose your Date :""",justify=LEFT,padx=20).pack( anchor = W )
count = 0
for date in list_date:
print count
R1=Radiobutton(frame, text=date, padx=20, value=count, variable=var, command=lambda:ShowChoice(var))
R1.pack()
count+=1
def ShowChoice(var):
print "option : " + str(var.get())
top = Tk()
var=IntVar()
The problem was with the instance of Tk() that I was creating.
Below link ( 1 ) said to use TopLevel() which solved the problem
Increment the counter in the function that is being called when the radio button is selected.
Here is an example to help you.It prints the number of times the button is selected.
import Tkinter as tk
count=0
root = tk.Tk()
def add():
global count
count=count+1
print count
v = tk.IntVar()
tk.Label(root,
text="""Choose a
programming language:""",
justify = tk.LEFT,
padx = 20).pack()
tk.Radiobutton(root,
text="Python",
padx = 20,
variable=v,
value=1,command=add).pack(anchor=tk.W)
root.mainloop()
The first set of code works. It displays the updating variable. However, in the second code, when I put the variable in a Treeview widget instead, the variable just stays on 0 and does not update. How come this works with the label but not with treeview? What is the easiest way to fix this?
First (works):
from tkinter import *
from tkinter import ttk
import threading
import time
def fun():
for i in range(10):
var.set(var.get() + 1)
time.sleep(.5)
t = threading.Thread(target=fun)
root = Tk()
var = IntVar()
var.set(0)
mainframe = ttk.Frame(root)
mainframe.grid(column = 0, row = 0)
label = ttk.Label(mainframe, textvariable=var)
label.grid(column = 0, row = 0)
t.start()
root.mainloop()
Second (does not work):
from tkinter import *
from tkinter import ttk
import threading
import time
def fun():
for i in range(10):
var.set(var.get() + 1)
time.sleep(.5)
t = threading.Thread(target=fun)
root = Tk()
var = IntVar()
var.set(0)
mainframe = ttk.Frame(root)
mainframe.grid(column = 0, row = 0)
tree = ttk.Treeview(mainframe, columns = ('number'), height = 1)
tree.insert('', 'end', text = 'Number', values = var.get())
tree.grid(column=0, row=0)
t.start()
root.mainloop()
modify fun to :
def fun():
for i in range(10):
var.set(var.get() + 1)
x = tree.get_children()
tree.item(x, text = 'Number', values = var.get())
time.sleep(.5)
The get_children method returns a list of tuples item IDs, one for each child of the tree. With tree.item then update the child with the required id.
In the second program along with the variable var, you also have to update the child of the tree
import tkinter as tk
panel = tk.Tk()
num = 42
lbl1 = tk.Label(panel, text = str(num))
Let's say I have a function and button like this:
def increase():
lbl1.configure(text = str(num+1))
btn = tk.Button(panel, text = 'Increase', command = increase)
panel.mainloop()
This button will make the number that is the label increase by 1 when pressing the button. However, this only works once before the button does absolutely nothing. How can I make it so that every time I press the button, the number increases by 1?
You never saved the incremented value of num.
def increase():
global num # declare it a global so we can modify it
num += 1 # modify it
lbl1.configure(text = str(num)) # use it
It's because num is always 43
import tkinter as tk
num = 42
def increase():
global num
num += 1
lbl1.configure(text = str(num))
panel = tk.Tk()
lbl1 = tk.Label(panel, text = str(num))
lbl1.pack()
btn = tk.Button(panel, text = 'Increase', command = increase)
btn.pack()
panel.mainloop()