Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'd like to get all file names in a directory and present them to user in a listbox, then user may choose multiple names and press OK or Cancel. If he presses OK, it should return selected file names. Please help.
here is a fairly simple way using Tkinter:
from Tkinter import *
root = Tk()
opt_list = ['opt1','opt2','opt3','opt4','opt5']
sel_list = []
def get_sel():
sel_list.append(Lb1.curselection())
root.destroy()
def cancel():
root.destroy()
B = Button(root, text ="Submit", command = get_sel)
C = Button(root, text ="Cancel", command = cancel)
Lb1 = Listbox(root, selectmode=MULTIPLE)
for i,j in enumerate(opt_list):
Lb1.insert(i,j)
Lb1.pack()
B.pack()
C.pack()
root.mainloop()
for i in sel_list[0]:
print opt_list[int(i)]
then you can this to get the selected options:
for i in sel_list[0]:
print opt_list[int(i)]
this will create a listbox using the items from sel_list then when the user presses submit it will return a tuple of which lines are selected
multiple can be selected at a time and will returned in a tuple get more information from this site Python Tk Tutorials Point
More specifically, what you want is http://tkinter.unpythonic.net/wiki/tkFileDialog
#python 3
from tkinter.filedialog import askopenfilename
filenames = askopenfilename(multiple=True)
This returns a list of paths to the files the person chose, to extract the filename:
import os
filenames = [os.path.basename(filename) for filename in filenames]
and if you want the filename without extension, instead of the line above use:
filenames = [os.path.splitext(os.path.basename(filename))[0] for filename in filenames]
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is my current db.py file, it contains the tkinter code for creating the GUI:
import tkinter
import db
app = Tk()
app.geometry("450x300")
app.mainloop()
You can use a Entry widget with a linked variable to get the input from user. The content can then be retrieved from the variable and written to a file using file objects.
I like to use themed-tkinter(ttk). If you just starting with creating GUI, I suggest you read more about themed-tkinter here.
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
# StringVar has all the logic to store and update string values
content = tk.StringVar()
def callback():
# This function is invoked when button `submit` is clicked
with open('content.txt', 'w') as file:
file.write(content.get())
entry = ttk.Entry(root, textvariable=content).grid()
submit = ttk.Button(root, text='submit', command=callback).grid()
root.mainloop()
Edit: I worded my answer wrongly for which I appologize. Tkinter by itself is indeed robust and powerful. I found it more easier to use ttk in many cases and had a softcorner towards it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I need to play a typewriter key sample on every tkinter.text input.
I came across the Playsound module but I don't know how to listen to the inputs.
You would use a bind and setup a function to play the sound when the bind is triggered.
import tkinter as tk
def key(event):
print("pressed", repr(event.char))
# Play sound here
root = tk.Tk()
text = tk.Text(root)
text.pack()
text.bind('<Key>', key)
root.mainloop()
Thanks, I've come up with a very similar solution tho its really really laggy. Im basically writing a simple typewriter emulator so the key sound is reproduced for each typed letter.
import tkinter as tk
from PIL import Image, ImageTk
from playsound import playsound
def key(event):
key = event.char
playsound("C:/Users/Isma/key1.mp3")
win = tk.Tk()
frame = tk.Frame(win, width=300, height=400)
frame.grid(row=1, column=0)
text = tk.Text(frame)
text.grid(row=0,column=0)
text.bind('<Key>',lambda a : key(a))
image = Image.open("C:/Users/Isma/swintec1.jpg")
photo = ImageTk.PhotoImage(image)
label = tk.Label(frame,image=photo)
label.image = photo
label.grid(row=3,column=0)
win.mainloop()
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am attempting to nest one ttk notebook within another so that I can have multiple tab levels.
Imagine an upper notebook with a tab for each food group, and within each of those foodgroup tabs, a tab for examples of foods in that group. A tabbed hierarchy.
Is it possible with ttk notebooks? I have not been able to find any reference or examples that deal with this question.
It seems like this code should work. I get no errors, but I can't see the second level tabs. Any help would be appreciated.
#import tkinter and ttk modules
from tkinter import *
from tkinter import ttk
#Make the root widget
root = Tk()
#Make the first notebook
nb1 = ttk.Notebook(root)
nb1.pack()
f0 = Frame(nb1)
f0.pack(expand=1, fill='both')
###Make the second notebook
nb2 = ttk.Notebook(f0)
nb2.pack()
#Make 1st tab
f1 = Frame(nb1)
#Add the tab to notebook 1
nb1.add(f1, text="First tab")
#Make 2nd tab
f2 = Frame(nb1)
#Add 2nd tab to notebook 1
nb1.add(f2, text="Second tab")
###Make 3rd tab
f3 = Frame(nb2)
#Add 3rd tab to notebook 2
nb2.add(f3, text="First tab")
###Make 4th tab
f4 = Frame(nb2)
#Add 4th tab to notebook 2
nb2.add(f4, text="Second tab")
root.mainloop()
Solved:
Here is the working code simplified with notation. Hopefully others will find it instructive. This example uses the model of College Program>Terms>Courses
#import tkinter and ttk modules
from tkinter import *
from tkinter import ttk
#Make the root widget
root = Tk()
#Make the first notebook
program = ttk.Notebook(root) #Create the program notebook
program.pack()
#Make the terms frames for the program notebook
for r in range(1,4):
termName = 'Term'+str(r) #concatenate term name(will come from dict)
term = Frame(program) #create frame widget to go in program nb
program.add(term, text=termName)# add the newly created frame widget to the program notebook
nbName=termName+'courses'#concatenate notebook name for each iter
nbName = ttk.Notebook(term)#Create the notebooks to go in each of the terms frames
nbName.pack()#pack the notebook
for a in range (1,6):
courseName = termName+"Course"+str(a)#concatenate coursename(will come from dict)
course = Frame(nbName) #Create a course frame for the newly created term frame for each iter
nbName.add(course, text=courseName)#add the course frame to the new notebook
root.mainloop()
This question already has answers here:
tkinter creating buttons in for loop passing command arguments
(3 answers)
How to pass arguments to a Button command in Tkinter?
(18 answers)
Closed 6 months ago.
how to change values in buttons done in a loop?
I mean a different text, a command for each of the resulting buttons.
the program counts files in a given folder, then this value is passed to the loop that displays the appropriate number of buttons.
here is the sample text:
files = os.listdir(".")
files_len = len(files) - 1
print(files_len)
def add():
return
for i in range(files_len):
b = Button(win, text="", command=add).grid()
You don't really need to change the Button's text, because you can just put the filename in when they're created (since you can determine this while doing so).
To change other aspects of an existing Button widget, like its command callback function, you can use the universal config() method on one after it's created. See Basic Widget Methods.
With code below, doing something like that would require a call similar to this: buttons[i].config(command=new_callback).
To avoid having to change the callback function after a Button is created, you might be able to define its callback function inside the same loop that creates the widget itself.
However it's also possible to define a single generic callback function outside the creation loop that's passed an argument that tells it which Button is causing it to be called — which is what the code below (now) does.
from pathlib import Path
import tkinter as tk
win = tk.Tk()
dirpath = Path("./datafiles") # Change as needed.
buttons = []
def callback(index):
text = buttons[index].cget("text")
print(f"buttons[{index}] with text {text!r} clicked")
for entry in dirpath.iterdir():
if entry.is_file():
button = tk.Button(win, text=entry.stem,
command=lambda index=len(buttons): callback(index))
button.grid()
buttons.append(button)
win.mainloop()
Try this. By making a list.
files = os.listdir(".")
files_len = len(files) - 1
print(files_len)
def add():
return
b=[]
for i in range(files_len):
b[i] = Button(win, text="", command=add).grid(row=i)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to make some basic GUI and I'm having some trouble with this code:
with open(project_dir + 'logs/wash.log') as f:
for line in f.readlines():
if not line.startswith('BSSID ') and \
not line.startswith('------------'):
print(line)
At this point of the application I have the tkinter root already opened in the background and a terminal opened too, I would like to open a new tkinter window in which display the line printed above, I suppose adding a label in the window for each line that I need to display.
I tried tk.Toplevel() but I don't know how to make the new window in which display the strings.
My problem is I am trying to create a new window and print the strings there, I have tried tk.Toplevel() but I don't know how to make the new window in which to display the strings
From your comment:
my problem is to create a new window and print there the strings, I tried tk.Toplevel() but I don't know how to make the new window in which display the strings
This is a simple example but should help.
I have a button on the root window that links to a function called new_window(). This function will create a top level window containing a text box widget. We then use the with open statement to write the data to the text box.
import tkinter as tk
root = tk.Tk()
def new_window():
top = tk.Toplevel(root)
my_text_box = tk.Text(top)
my_text_box.pack()
with open(project_dir + 'logs/wash.log') as f:
for line in f.readlines():
if not line.startswith('BSSID ') and \
not line.startswith('------------'):
my_text_box.insert("end", line)
open_new_window = tk.Button(root, text="Open Toplevel", command=new_window)
open_new_window.pack()
root.mainloop()