So I have a program that is basically supposed to have a button that opens a file dialog in the (username) folder. But when I run the program it opens without even pushing the button. What's more, the button doesn't even show up. So in addition to that problem I have to find a way to turn the selected directory into a string.
import tkinter
import tkinter.filedialog
import getpass
gui = tkinter.Tk()
user = getpass.getuser()
tkinter.Button(gui, command=tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user)).pack()
gui.mainloop()
Regarding your first issue, you need to put the call to tkinter.filedialog.askopenfilename in a function so that it isn't run on startup. I actually just answered a question about this this morning, so you can look here for the answer.
Regarding your second issue, the button isn't showing up because you never placed it on the window. You can use the grid method for this:
button = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))
button.grid()
All in all, your code should be like this:
import tkinter
import tkinter.filedialog
import getpass
gui = tkinter.Tk()
user = getpass.getuser()
button = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))
button.grid()
gui.mainloop()
You forgot to use a geometry manager on the button:
button = tkinter.Button(window, command=test)
button.pack()
If you don't do it, the button won't be drawn. You might find this link useful: http://effbot.org/tkinterbook/pack.htm.
Note that to pass the command to handler you have to write only the name of the function (Like it's descibed in the other answer).
This is an old question, but I just wanted to add an alternate method of preventing Tkinter from running methods at start-up. You can use Python's functools.partial (doc):
import tkinter
import tkinter.filedialog
import getpass
import functools
gui = tkinter.Tk()
user = getpass.getuser()
button = tkinter.Button(
gui,
command=functools.partial(
tkinter.filedialog.askopenfilename,
initialdir='C:/Users/%s' % user)
)
button.grid()
gui.mainloop()
Related
I have a login screen that once logged in will take me to a page that has two buttons. Canteen page button, and admin page button.
my first problem is that once I open my canteen page by pressing the button everything that's inside this page doesn't seem to be working. I assume I have to 'import * from Canteen' although I cant import all under a module.
my second problem is the same as the first just with my Admin screen.
def adminpage():
import Admin
def canteenpage():
import Canteen
find_user = ('SELECT * FROM user WHERE username = ? and password = ?')
c.execute(find_user,[(self.username.get()),(self.password.get())])
result = c.fetchall()
if result:
root=Tk()
root.geometry("400x400")
root.title("Select Page")
Label(text = "welcome to the dashboard").pack()
Button(root, text = "Canteen Page",command=canteenpage).pack()
Button(root, text = "Admin Page",command=adminpage).pack()
As my comment stated if you would like to import the contents of a module you do from Canteen import *
However I don't think importing a module would encapsulate the behaviour you would like to achieve. Your code seems to suggest that you would like to serve the result of a database query in a new window.
For that kind of behaviour I suggest checking out either message widget or messagebox widget of tkinter and adapt your code to use either one of them.
You should put all the code in the other module(In your case "Admin" and "Canteen") in a class. That would work for you.
Like I have done in this example:
Module_1:
import tkinter as tk
def test_func():
from Module_2 import TestClass
root = tk.Tk()
b = tk.Button(root, text="Click", command=lambda: test_func())
b.pack()
root.mainloop()
Module_2:
class TestClass:
import tkinter as tk
root = tk.Toplevel()
lbl = tk.Label(root, text="Test Label")
lbl.pack()
This will work for you
So you know how when you use Notepad (on Windows), for example, and you want to open an old file? You click file, then open, then a file dialog opens ups and you can select the file you want, and the program will display its contents.
Basically, I want to make a button in Python that can do that exact thing.
Here's my function for the button-
def UploadAction():
#What to do when the Upload button is pressed
from tkinter import filedialog
When I click on the button assigned to this action, nothing happens, no errors, no crash, just nothing.
import tkinter as tk
from tkinter import filedialog
def UploadAction(event=None):
filename = filedialog.askopenfilename()
print('Selected:', filename)
root = tk.Tk()
button = tk.Button(root, text='Open', command=UploadAction)
button.pack()
root.mainloop()
I've read some post on stack overflow,Issues intercepting subprocess output in real time, Redirect command line results to a tkinter GUI, i know i have to use threading and queue in tkinter, but I am still can't do the same thing because I am a beginner in program,please help.
The goal: When press a button, getting the 'top' command output and realtime display in tkinter text widget
The issue: I've tried to follow the code, but still cannot get the output, but I have not idea how to make it work.
from tkinter import *
import tkinter as tk
import subprocess
from threading import Thread
from queue import Queue
window = tk.Tk()
window.title('realtime')
window.geometry('800x400')
text = tk.Text(window)
text.pack()
button = tk.Button(window, text= 'Press')
button.pack()
window.mainloop()
This is only the gui outlook, please help
top refreshes itself now and then and I'm guessing that's the behavior you want to capture with threading and whatnot. However in this case it would be much easier to ask top to only run once, and have tkinter do the timing and refreshing:
import tkinter as tk
from sh import top
def update_text():
text.delete(0.0, tk.END)
text.insert(0.0, top('-b', n=1))
window.after(1000, update_text) # call this function again in 1 second
window = tk.Tk()
window.title('realtime')
window.geometry('800x400')
text = tk.Text(window)
text.pack()
button = tk.Button(window, text= 'Press', command=update_text)
button.pack()
window.mainloop()
You may need to install sh to run top like I did, or use subprocess.check_output if you want.
text.insert(0.0, subprocess.check_output(['top', '-b', '-n 1']))
I'm using jupyter notebook on mac, recently I need to write interactive dialog box, so after google, I use Tkinter to make an interactive window.
But I was bothered by this problem couples day ,and still can't find a solution way.
Fisrt example:
from Tkinter import *
from tkFileDialog import askopenfilename
import sys
import os,time
def callback():
name= askopenfilename()
print name
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
Second example:
from Tkinter import *
import sys,os
class YourApp(Tk):
def quit_and_close(self):
app.quit()
#os._exit(0)
#sys.exit(1)
#exit(0)
app = YourApp()
app.title('example')
app.geometry('400x300+200+200')
b = Button(app, text = "quit", command = app.quit_and_close)
b.pack()
app.mainloop()
And the third one:
import Tkinter as tk
import tkMessageBox
def ask_quit():
if tkMessageBox.askokcancel("Quit", "You want to quit now? *sniff*"):
root.destroy()
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", ask_quit)
root.mainloop()
After running those above code, always need have to force quit python launcher.
It is very weird, and annoying because after forcing quit, I will got the error:
Is it necessary to use python launcher as default window?
Is there possible to set another window to open ?
or is there proper way to close the launcher without causing programming crash?
p.s Even I try to use wxpython, it still open python launcher and got the same problem.
I am new to Tkinter and GUI design but I'm definitely excited to learn. I'm trying to create a user interface that allows a user to load an excel spreadsheet .xls. If the spreadsheet is successfully opened then a button should pop up allowing the user to import information into a database.
My problem is that whenever I run this code the file dialog pops up before the main gui with the actual browse button pops up. I did some tests and this behavior is due to calling fname.show(). The thing is, and please correct me if I'm wrong, I need to use fname.show() to get the filepath so that I can pass the filepath into the xlrd.open_workbook method to read data from the spreadsheet. Is there another way of getting the filename? I feel like there should be an easy solution but there isn't much in terms of documentation on the specifics of tkFileDialog.
Thanks.
Below is my code:
import config
from importdb import importTLAtoDB
import Tkinter as tk
import tkFileDialog as tkfd
import tkMessageBox as tkmb
import xlrd
def openFile():
#returns an opened file
fname = tkfd.Open(filetypes = [("xls files","*.xls")])
fpath = fname.show()
if fname:
try:
TLA_sheet = xlrd.open_workbook(fpath).\
sheet_by_name('Q3 TLA - TOP SKUs')
tk.Button(root, text = "Import TLAs", command = importTLAtoDB(TLA_sheet)).pack()
tkmb.showinfo("Success!", "Spreadsheet successfully loaded. \n\
Click Import TLAs to load TLA info into RCKHYVEDB database.")
except:
tkmb.showerror("Error", "Failed to read file\n '%s'\n\
Make sure file is a type .xls" % fpath)
#GUI setup
root = tk.Tk()
root.title("TLA Database Tool")
tk.Button(root, text = "Browse", command = openFile(), width = 10).pack()
root.mainloop()
When you do, command = importTLAtoDB(TLA_sheet) you call the function and assign functions' value to command.
If you want to call a function with an argument, you need to use lambda or partials(there might be other options but these two are most preferred ones as far as I know).
So your Button line should be like this:
tk.Button(root, text="Import TLAs", command=lambda: importTLAtoDB(TLA_sheet)).pack()
Also, you may want to check this question. How to pass arguments to a Button command in Tkinter?
tk.Button(root, text = "Browse", command = openFile, width = 10).pack()
you dont want to actually call it when you setup the button