I am starting in tkinter and I have generated a list with the elements that are in a certain folder and I need to show them in the interface.
I put it in a label but it shows me the elements horizontally and I need it to show one below the other, is there a way to do this?
from tkinter import *
from os import listdir
raiz = Tk()
ruta = './imagenes'
fotos = Frame()
fotos.place(x=0,y=0)
fotos.config(bd=10,relief="groove",width="500", height="200")
fotografias = StringVar()
lblfotos = Entry(fotos, textvariable=fotografias)
lblfotos.config(width="75")
lblfotos.place(x=10,y=0)
fotografias.set(listdir(ruta))
raiz.mainloop()
https://i.stack.imgur.com/JaEek.png
[1]: P.S. The original idea is that the files in the folder are displayed in the interface and you can interact with them, such as opening or deleting, but I didn't find how, could that be done in tkinter? or maybe in another library?. Thank you for your answer.
An Entry widget can only hold single line of string. Use Listbox widget instead. Also avoid using wildcard import and it is better to use pack() or grid() instead of place() in normal case.
Below is an example based on your code:
import tkinter as tk
from os import listdir
raiz = tk.Tk()
ruta = './imagenes'
fotos = tk.Frame(raiz, bd=10, relief="groove")
fotos.pack(fill="both", expand=1)
lblfotos = tk.Listbox(fotos, width=30, height=20)
lblfotos.pack(fill="both", expand=1)
for imgfile in listdir(ruta):
lblfotos.insert("end", imgfile)
raiz.mainloop()
Related
I'm trying to make a simple outline for a gui, and I'm getting the warning
"variable" May be undefined or defined from star imports: tkinter for all of my variables.
Here is my code:
from tkinter import *
class myApp :
def __init__(self, gui,) :
self.root = gui
self.bframe = Frame(self.root) # Create a container Frame at bottom
self.bframe.pack(side=BOTTOM)
self.xlabel = Label(self.root, text="Item ID") # Create the Label
self.xlabel.pack(side=LEFT)
self.xentry = Entry(self.root, bd=5) # Create the Entry box
self.xentry.pack(side=LEFT)
self.xentry.bind('<Return>', self.showStockItem)
self.xentry.focus_set() # Set focus in the Entry box
self.xopen = Button(self.root, text="Show", command=self.showStockItem) # Create the open Button
self.xopen.pack(side=LEFT)
self.xquit = Button(self.bframe, text="Quit", command=self.quitit) # Create the quit Button
self.xquit.pack(side=BOTTOM)
return
gui = Tk()
gui.title("Travel")
app = myApp(gui)
gui.mainloop()
from tkinter import *
In this line, you import everything from tkinter. This is not recommended, so linter will warn you. But if you really want to do this, it's OK, just ignore it.
To be better, you should explicitly import what you need. For example:
from tkinter import Tk, Label, Frame, Entry, Button
Consider using:
import tkinter as tk
and then, prefix all your calls like:
root = tk.Tk()
or,
variableName.pack(side = tk.LEFT)
and so on...
I want to create a tkinter window, where it will appear the files of a folder as a dropdown menu and a Select button, such that when I select an element from the previous list the full path will be saved into a new variable. Apparently, I need to give an appropriate command.
from Tkinter import *
import tkFileDialog
import ttk
import os
indir= '/Users/username/results'
root = Tk()
b = ttk.Combobox(master=root, values=os.listdir(indir)) # This will create a dropdown menu with all the elements in the indir folder.
b.pack()
w = Button(master=root, text='Select', command= ?)
w.pack()
root.mainloop()
I think what you need here is actually a binding. Button not required.
Here is an example that will list everything in your selected directory and then when you click on it in the Combo Box it will print out its selection.
Update, added directory and file name combining to get new full path:
from Tkinter import *
import tkFileDialog
import ttk
import os
indir= '/Users/username/results'
new_full_path = ""
root = Tk()
# we use StringVar() to track the currently selected string in the combobox
current_selected_filepath = StringVar()
b = ttk.Combobox(master=root, values=current_selected_filepath)
function used to read the current StringVar of b
def update_file_path(event=None):
global b, new_full_path
# combining the directory path with the file name to get full path.
# keep in mind if you are going to be changing directories then
# you need to use one of FileDialogs methods to update your directory
new_full_path = "{}{}".format(indir, b.get())
print(new_full_path)
# here we set all the values of the combobox with names of the files in the dir of choice
b['values'] = os.listdir(indir)
# we now bind the Cobobox Select event to call our print function that reads to StringVar
b.bind("<<ComboboxSelected>>", update_file_path)
b.pack()
# we can also use a button to call the same function to print the StringVar
Button(root, text="Print selected", command=update_file_path).pack()
root.mainloop()
Try something like this:
w = Button(master=root, text='Select', command=do_something)
def do_something():
#do something
In the function do_something you create what you need to get the full path. You can also pass vars into the command.
get()
Returns the current value of the combobox.(https://docs.python.org/3.2/library/tkinter.ttk.html)
from Tkinter import *
import tkFileDialog
import ttk
import os
indir= '/Users/username/results'
#This function will be invoked with selected combobox value when click on the button
def func_(data_selected_from_combo):
full_path = "{}/{}".format(indir, data_selected_from_combo)
print full_path
# Use this full path to do further
root = Tk()
b = ttk.Combobox(master=root, values=os.listdir(indir)) # This will create a dropdown menu with all the elements in the indir folder.
b.pack()
w = Button(master=root, text='Select', command=lambda: func_(b.get()))
w.pack()
root.mainloop()
I tried the below code but the buttons are placed only at the center only,it is not placed according to my required positioning
from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image
root = Tk()
def DT(event):
print "Decision tree is selected"
button3 = Button(root, text="Decision Tree",font=("Helvetica", 15))
button3.place(x=50,y=220)
button3.pack()
button3.bind('<Button-1>', DT)
root.minsize(width=1300, height=700)
#root.configure(background='lavender')
root.mainloop()
button3.pack() overrides the placement made by button3.place().
Delete the button3.pack() line.
You are placing and packing the button. Just use either place or pack.
I'm still quiet new to programming, so maybe my question in pretty easy or even stupid. As said in the title I'm trying to programm a for loop, which creates a pictured button widget for each picuture in a certain folder. This is what I have so far:
import tkinter
from tkinter import ttk
from tkinter import PhotoImage
import os
root = tkinter.Tk()
list_files = os.listdir(".")
for file in list_files:
if file.endswith(".gif"):
drink = PhotoImage(file)
print(drink)
b1 = ttk.Button(image=drink, text="Hello", compound="right").pack()
l1 = ttk.Label(image=drink).pack()
root.mainloop()
Now what I get is two widgets, one label displaying nothing and a button displaying Hello. In the shell it says drink1.gif, which is correct, because that's the only gif file in my standard python folder...
what have I done wrong?
Use PhotoImage(file='path_to_file') to create image from path.
When PhotoImage object is garbage-collected by Python, the label is cleared. You must save reference to drink object somewhere: l1.image = drink:
http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
widget.pack() method return nothing.
import tkinter
from tkinter import ttk
from tkinter import PhotoImage
import os
root = tkinter.Tk()
list_files = os.listdir(".")
for path in list_files:
if path.endswith(".gif"):
drink = PhotoImage(file=path)
b1 = ttk.Button(root, image=drink, text="Hello", compound="right")
b1.pack()
l1 = ttk.Label(root, image=drink)
l1.image = drink
l1.pack()
root.mainloop()
PhotoImage(file) creates an image and gives it the name "drink1.gif", which is returned. If you actually want to load the file into the image, you need PhotoImage(file = file).
I believe you are supposed to run self.pack, according to the Zetcode tutorial.
I want to change bg color of tkSimpleDialog to match my system default bg color:
GTK:
tk:
I tried to put config(bg='#CCC9C1') everywhere I can think of, but I managed to make only for some parts from dialog.
Is it possible to change bg color in tkSimpleDialog?
Code sample:
from Tkinter import *
import tkSimpleDialog
class MyDialog(tkSimpleDialog.Dialog):
def body(self, master):
Label(master, text="First:").grid(row=0)
Label(master, text="Second:").grid(row=1)
self.e1 = Entry(master)
self.e2 = Entry(master)
self.e1.grid(row=0, column=1)
self.e2.grid(row=1, column=1)
return self.e1 # initial focus
def apply(self):
first = int(self.e1.get())
second = int(self.e2.get())
print first, second # or something
root = Tk()
root.withdraw()
d = MyDialog(root)
Found way out. As mentioned root.config(...) changes appearance just on root window (side window that we always usually hide). For global settings we are encouraged to use Tk database file (i.e. named optionDB) which has same format as .Xdefaults (X resource database) file. Then we use it in a script like this:
root = Tk()
root.option_readfile('optionDB')
Even better, for some reason discouraged, we can set 'global' settings in a script directly:
root = Tk()
root.option_add('*background', '#CCC9C1')
root.option_add('*Entry*background', '#FFFFFF')
Available keywords are:
*font
*Label*font
*background
*Entry*background
*foreground
*Listbox*foreground
It looks like you may just need to use the tkinter.ttk library, which is the themed version of Tk as shown in this answer. Hope it helps.
Here's the reference for Python 2.x, currently 2.7: http://docs.python.org/library/ttk.html