This question already has answers here:
tkinter creating buttons in for loop passing command arguments
(3 answers)
Closed 6 months ago.
from tkinter import *
root = Tk()
def oku():
l1=Label(root,text=0)
myfilerr=open("kayit.txt","r")
content=myfilerr.readlines()
myfilerr.close()
return content
def kisiSec(kisi):
okudeg=oku()
print(kisi)
def main():
i=0
okudeg=oku()
menubar = Menu(root)
menu2=Menu(menubar,tearoff=0)
for i in okudeg:
menu2.add_command(label=i, command=lambda: kisiSec(i))
root.config(menu=menubar)
menubar.add_cascade(label="Kişiler", menu=menu2)
main()
root.mainloop()
Dont judge me im new but there are 3 diffrent names in the text but in main, c1 buttons gives out same name to kisisec()
How can i fix that?
--ITS TURKISH--
use this:
lambda i=i:
in for loop, because something about the reference to the incorrect thing, so you need to save it in the lambda, for the function to access the parameter.
Related
This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed last year.
I'm making a log/chat system in my program (just Tkinter default looks) and i came across a problem where I can't add or change a listbox. Here is what I'm trying to do:
import tkinter
from tkinter import *
from tkinter import messagebox
import random
window = tkinter.Tk()
window.geometry("250x195")
window.title(" ")
window.iconbitmap("icon.ico")
global loglength, log
log = []
loglength = len(log)
inventorylist = []
def sendmessage(event):
chatstring = chatentry.get()
log.append(chatstring)
print(log, loglength)
checknew() #dont worry abt this it works
serverlog = tkinter.Listbox(
width=20,
height=11,
bg="darkgray",
listvariable=log
).place(x=128,y=-2)
I want to add items to the listbox. Here is an image of my program:
When I press enter (the key bound to the function to add the string to the listbox) this happens:
is Listbox like a program u want?
if u want a program that will make u program list in tkinder this is the code :
from tkinter import *
a= Tk()
a.geometry("400x400")
a.title("test")
Lb1 = Listbox(a,bg = "pink", bd = 10, fg = "black",\
font = "Castellar", cursor = "target")
Lb1.insert(1, "lion")
Lb1.insert(2, "tiger")
Lb1.insert(3, "zebra")
Lb1.insert(4, "elephant")
Lb1.insert(5, "deer")
Lb1.insert(6, "fox")
Lb1.insert(7, "Wolf")
Lb1.insert(8, "Gorilla")
Lb1.insert(9, "Jackal")
Lb1.insert(10, "Otter")
Lb1.pack()
a.mainloop()
hope that i helped u.
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 2 years ago.
I am trying to create a simple "Store App" that will add the item name and cost to a dictionary and then output it, but whenever I go to run my program it adds both items to cart before I have even clicked the buttons. I am not sure if it is a python problem, or something to do with how Tkinter works. Any help would be appreciated.
from tkinter import *
root = Tk()
root.title("Number Sorter")
root.geometry('600x600')
cart_list = {"Item_Name": [], "Price": []}
def purchaseClick(Name, Price):
cart_list["Item_Name"].append(Name)
cart_list["Price"].append(Price)
title1 = Label(root, text="The Solar War by A.G Riddle")
item1_name = "The Solar War"
item1_price = 11.99
title1.pack()
purchasebtn = Button(root, text="Purchase", command = purchaseClick(item1_name, item1_price))
purchasebtn.pack()
title2 = Label(root, text="Elon Musk By Ashlee Vance")
item2_name = "Elon Musk"
item2_price = 9.99
title2.pack()
purchasebtn = Button(root, text="Purchase", command = purchaseClick(item2_name, item2_price))
purchasebtn.pack()
cart_list_show = Label(root, text=cart_list)
cart_list_show.pack()
root.mainloop()
This is happening because Button.command takes a function as an argument, not the output. So, you have to pass just purchaseClick and not purchaseClick(item1, price1).
But in your case you need to pass in arguments too, so change the line from
purchasebtn = Button(root, text="Purchase", command = purchaseClick(item1_name, item1_price))
to this,
purchasebtn = Button(root, text="Purchase", command = lambda : purchaseClick(item1_name, item1_price))
I am fairly sure this is gonna do the work for you.
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 3 years ago.
I'm playing around with TKinter trying to make a number generator.
I can't figure out why a new number doesn't get generated when I use this code:
roll = Button(window, text = 'Roll!', command = num())
But it works if I remove the brackets:
roll = Button(window, text = 'Roll!', command = num)
Thanks guys!
Rest of the code:
from tkinter import *
import random
def num():
number = random.randint(1, 6)
num1.configure(text = number)
return
window = Tk()
window.geometry('300x200')
window.title('Dice')
num1 = Label(window, text = 0)
num1.grid(column = 0, row = 0)
roll = Button(window, text = 'Roll!', command = num)
roll.grid(column = 0, row = 1)
window.mainloop()
When you write num() with the parentheses, you're calling the function immediately, and passing its return value as the argument to Button. When you just name the function, you're passing the function object itself as the argument to Button, and it will call the function later (when the button is clicked).
This question already has answers here:
tkinter creating buttons in for loop passing command arguments
(3 answers)
Closed 6 months ago.
I run into small problem trying to create 0-9 number buttons. I want to define 10 buttons for numbers from 0 to 9 in single loop. Each of them is supposed to add its value to self.user_input = tk.StringVar() which will be printed in label. Clicking 5 button, 7 button and then 0 button will give output 570. I try to use lambda to create command for each button, but instead of getting different values I have 9 everywhere. Here is my code:
import tkinter as tk
import tkinter.ttk as ttk
class Gui(tk.Tk):
def __init__(self):
super().__init__()
self.user_input = tk.StringVar()
tk.Label(self, textvariable=self.user_input).grid()
self.create_buttons()
def create_buttons(self):
for x in range(10):
ttk.Button(self, text=x, command=lambda: self.user_input.set(self.user_input.get() + str(x))).grid()
app = Gui()
app.mainloop()
How can I fix code above to make it work as expected (description up)?
Put the bulk of your code in a proper function. A best practice is that a lambda for a widget callback should only ever call a single function. Complex lambdas are difficult to read and difficult to debug.
The second part of the solution is to create a closure. The trick for that is to make the variable you're passing in bound to the lambda as a default argument.
The callback looks something like this:
def callback(self, number):
new_value = self.user_input.get() + str(number)
self.user_input.set(new_value)
Defining each button looks something like this:
def create_buttons(self):
for x in range(10):
button = ttk.Button(self, text=x, command=lambda number=x: self.callback(number))
button.grid()
Pay particular attention to number=x as part of the lambda definition. This is where the current value of x is bound to the number parameter inside the lambda.
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 7 years ago.
My program draws the fractal using pointSize_max and pointSize variables, which are entered by the user in Tkinter. The problem is that the fractal is drawn before pressing a button (as soon as the program is run), and the program does not draw the fractal when the button is pressed.
pointLabel = tk.Label(frame,text="minimaalne pikkus")
pointLabel.pack()
pointSize = tk.StringVar()
pointEntry = tk.Entry(frame,textvariable=pointSize)
pointEntry.pack()
pointSize.set(str(10))
pointLabel_max = tk.Label(frame,text="maksimaalne pikkus")
pointLabel_max.pack()
pointSize_max = tk.StringVar()
pointEntry_max = tk.Entry(frame,textvariable=pointSize_max)
pointEntry_max.pack()
pointSize_max.set(str(30))
drawButton = tk.Button(frame, text = "Draw a fractal", command=koch(int(pointSize_max.get()), int(pointSize.get())))
# koch function draws the fractal
drawButton.pack()
tk.mainloop()
The koch function is called when the button is created, as part of the parameter evaluation before the tk.Button call. You can create a function object to call instead.
def koch_invoke():
koch(int(pointSize_max.get()), int(pointSize.get()))
drawButton = tk.Button(frame, text = "Draw a fractal", command=koch_invoke)
When your script is compiled it comes to this line and runs the function since you are calling it:
command=koch(int(pointSize_max.get()), int(pointSize.get()))
Try using a lambda to prevent this from happening:
command= lambda x = int(pointSize_max.get()), y = int(pointSize.get()): koch(x, y))