So I have been coding a search bar type thing in Python because I was bored and all. And when searching something with it, it opens in Internet Explorer instead of my default browser (Chrome).
from tkinter import *
import webbrowser
win = Tk()
win.title("Search Bar")
def search():
url = entry.get()
webbrowser.open(url)
label1 = Label(win,text="Enter URL Here : "
,font=("arial",10,"bold"))
label1.grid(row=0,column=0)
entry = Entry(win,width=30)
entry.grid(row=0,column=1)
button = Button(win,text="Search",command=search)
button.grid(row=1,column=0,columnspan=2,pady=10)
win.mainloop()
try like this
webbrowser.get('chrome').open('https://stackoverflow.com/')
OR
webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open("http://google.com")
Related
I'm a super beginner with Python, so please be kind.
I am creating an app that should take in user input from text boxes, and then when the user presses the submit button this is saved in a text file.
I think the issue is that I'm not quite sure how to create the right function for the pushbutton command.
I would really appreciate if someone can code a simple app showing how to do this.
This is the code I have so far, but I get an error "TypeError: write() argument must be str, not TextBox".
from guizero import *
import os
cwd = os.getcwd()
# function for writing files
def save_file():
with open(cwd+'/Desktop/File handling/newfile.txt','a') as f:
f.write(userInput)
app = App("testing")
userInput = TextBox(app)
submit_button = PushButton(app, command=save_file, text="submit")
app.display()
`
I figured it out. Thanks :)
from guizero import *
import os
cwd = os.getcwd()
# function for writing files
def save_file():
with open(cwd+'/Desktop/File handling/newfile.txt','a') as f:
f.write("First name:"+" "+first_name.value+"\n")
#the app
app = App("testing")
#text box
first_name = TextBox(app, width=30, grid=[2,4])
#submit button
box = Box(app)
submitbutton = PushButton(app, command=(save_file), text="Submit")
app.display()
from tkinter import *
from tkinter import filedialog
def openFile():
global pathFile
file_path = filedialog.askopenfilename()
path.set(file_path)
pathFile = path.get()
#file_name = ' for example google chrome'
root = Tk()
path = StringVar()
button = Button(text="Choose a program", command=openFile)
button.pack()
root.mainloop()
For example lets say the user chooses to pick chrome.exe, I want the name Google Chrome to be saved in the file_name variable. How can I do that.
Edit: I dont wan't to use the os.path.basename method,the name should be whatever is typed here
Screenshot 1
Screenshot 2
Environment
Python 3.6.2
Windows 10
The Problem
I use the tk method clipboard_append() to copy a string to the clipboard.
When my program is run from the Python interpreter data is copied to the clipboard correctly.
When run using "C:\Python36.exe myprogram.py" however, I get some weird behavior.
If I paste the data while the program is still running, it works as expected.
If I paste the data while the program is running, then close the program, I can continue to paste the data.
If I close the program after copying but before pasting, the clipboard is empty.
Question
How do I make tk copy to the clipboard regardless of what happens to the containing window?
My Code
from tkinter import *
from tkinter import messagebox
url = 'http://testServer/feature/'
def copyToClipboard():
top.clipboard_clear()
top.clipboard_append(fullURL.get())
top.update()
top.destroy()
def updateURL(event):
fullURL.set(url + featureNumber.get())
def submit(event):
copyToClipboard()
top = Tk()
top.geometry("400x75")
top.title = "Get Test URL"
topRow = Frame(top)
topRow.pack(side = TOP)
bottomRow = Frame(top)
bottomRow.pack(side = BOTTOM)
featureLabel = Label(topRow, text="Feature Number")
featureLabel.pack(side = LEFT)
featureNumber = Entry(topRow)
featureNumber.pack(side = RIGHT)
fullURL = StringVar()
fullURL.set(url)
fullLine = Label(bottomRow, textvariable=fullURL)
fullLine.pack(side = TOP)
copyButton = Button(bottomRow, text = "Copy", command = copyToClipboard)
copyButton.pack(side = TOP)
featureNumber.focus_set()
featureNumber.bind("<KeyRelease>", updateURL)
featureNumber.bind("<Return>", submit)
top.mainloop()
Purpose of the Program
My company has a test server we use for new features. Every time we create a new feature we need to post a url to it on the test server. The urls are identical save for the feature number, so I created this python program to generate the url for me and copy it to the clipboard.
I can get this working if I comment out "top.destroy" and paste the url before manually closing the window, but I would really like to avoid this. In a perfect world I would press a shortcut, have the window pop up, enter my feature number, then just press enter to close the window and paste the new url, all without taking my hands off the keyboard.
Your issue about the clipboard being empty if you close the tk app before pasting the clipboard is due to an issue in tkinter itself. This has been reported a few times and it has to due with the lazy way tkinter handles the clipboard.
If something is set to the tkinter clipboard but is not pasted then tkinter will not append the windows clipboard before the app is closed. So one way around that is to tell tkinter to append to the windows clipboard.
I have been testing a method to do that however it is causing some delay in the applications process so its probably not the best solution but is a start. Take a look at this modified version of your code using the import os with the system method.
from tkinter import *
from tkinter import messagebox
import os
top = Tk()
top.geometry("400x75")
top.title = "Get Test URL"
url = 'http://testServer/feature/'
fullURL = StringVar()
fullURL.set(url)
def copyToClipboard():
top.clipboard_clear()
top.clipboard_append(fullURL.get())
os.system('echo {}| clip'.format(fullURL.get()))
top.update()
top.destroy()
def updateURL(event):
fullURL.set(url + featureNumber.get())
def submit(event):
copyToClipboard()
topRow = Frame(top)
topRow.pack(side = TOP)
bottomRow = Frame(top)
bottomRow.pack(side = BOTTOM)
featureLabel = Label(topRow, text="Feature Number")
featureLabel.pack(side = LEFT)
featureNumber = Entry(topRow)
featureNumber.pack(side = RIGHT)
fullLine = Label(bottomRow, textvariable=fullURL)
fullLine.pack(side = TOP)
copyButton = Button(bottomRow, text = "Copy", command = copyToClipboard)
copyButton.pack(side = TOP)
featureNumber.focus_set()
featureNumber.bind("<Return>", submit)
top.mainloop()
When you run the code you will see that the code freezes the app but once its finishes processing after a few seconds it will have closed the app and you can still paste the clipboards content. this servers to demonstrate that if we can write to the windows clipboard before the tkinter app is closed it will work as intended. I will look for a better method but this should be a starting point for you.
Here is a few links of the same issue that has been reported to tkinter.
issue23760
1844034fffffffffffff
732662ffffffffffffff
822002ffffffffffffff
UPDATE:
Here is a clean solution that uses the library pyperclip
This is also cross platform :)
from tkinter import *
from tkinter import messagebox
import pyperclip
top = Tk()
top.geometry("400x75")
top.title = "Get Test URL"
url = 'http://testServer/feature/'
fullURL = StringVar()
fullURL.set(url)
def copyToClipboard():
top.clipboard_clear()
pyperclip.copy(fullURL.get())
pyperclip.paste()
top.update()
top.destroy()
def updateURL(event):
fullURL.set(url + featureNumber.get())
def submit(event):
copyToClipboard()
topRow = Frame(top)
topRow.pack(side = TOP)
bottomRow = Frame(top)
bottomRow.pack(side = BOTTOM)
featureLabel = Label(topRow, text="Feature Number")
featureLabel.pack(side = LEFT)
featureNumber = Entry(topRow)
featureNumber.pack(side = RIGHT)
fullLine = Label(bottomRow, textvariable=fullURL)
fullLine.pack(side = TOP)
copyButton = Button(bottomRow, text = "Copy", command = copyToClipboard)
copyButton.pack(side = TOP)
featureNumber.focus_set()
featureNumber.bind("<Return>", submit)
top.mainloop()
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
I have a tkinter script. I was wondering is there anyway to have is so when you hit a button it takes you to a Web Site
from tkinter import *
app = Tk()
app.geometry("250x400")
app.title("Links")
def Link():
?
button1 = Button(app, text = "To a web site.", command = Link)
button1.pack()
app.mainloop()
There's a module for that.
import webbrowser
webbrowser.open("http://xkcd.com/353/")
Use webbrowser module to open the URL. The documentation: https://docs.python.org/3/library/webbrowser.html
# You can use open
from webbrowser import open
def link():
open('https://www.youtube.com/')
# You can use open_new_tab
from webbrowser import open_new_tab
def link():
open_new_tab('https://www.youtube.com/')