from tkinter import *
from tkinter import ttk
import webbrowser
import urllib
root = Tk()
w = Label(root, text="Where can I take you?")
w.pack()
url = 'http://sampdm.net/member.php?action=profile&uid=1'
def Openurl(url):
webbrowser.open_new(url)
button = Button(root, text = "Open Owners Profile #1", command = lambda:
Openurl(url))
button.pack()
root.mainloop()
Is there any way to make another button with another link like it?
I know there will be but I can't seem to figure out
From reading the comments it looks like you are not sure how to create multiple buttons inside your Tkinter window.
Its really easy and all you need to do is repeat the process that you used to create your first button.
I will provide 2 examples.
Here is how you can create each button manually for each website you wish to provide a button for.
from tkinter import *
import webbrowser
root = Tk()
url = 'http://sampdm.net/member.php?action=profile&uid=1'
url2 = 'www.google.com' # assign any variable name you want.
some_other_url = 'https://www.yahoo.com/'
def Openurl(url):
webbrowser.open_new(url)
w = Label(root, text="Where can I take you?")
w.pack()
# Here you can keep creating buttons using the same method as the first button.
# Just make sure you assign the correct url variable to the command.
button = Button(root, text = "Open Owners Profile #1", command = lambda: Openurl(url)).pack()
button2 = Button(root, text = "Open Google", command = lambda: Openurl(url2)).pack()
some_other_button = Button(root, text = "Open something else", command = lambda: Openurl(some_other_url)).pack()
root.mainloop()
Here is an example where your buttons are created from a list. This is a simple example but it should be enough to illustrate how it can be done.
from tkinter import *
import webbrowser
root = Tk()
# Here we create a list to use in button creation.
url_list = ['www.google.com', 'www.yahoo.com']
w = Label(root, text="Where can I take you?")
w.pack()
def Openurl(url):
webbrowser.open_new(url)
def create_buttons():
for url in url_list: # for each string in our url list
# creating buttons from our for loop values that will pack
# in the order they are created.
Button(root, text = url, command = lambda u = url: Openurl(u)).pack()
create_buttons()
root.mainloop()
Related
I have two widgets to work with, a text input, and a button, both are created inside a function. What I want to happen is the user types in their name and then clicks the button to submit the answer. What I want the computer to do, is on the button press it will read whats inside the text and the save it to a variable. Once it saves it, it will print it out.
The code below is bad because it runs through the if statement immediately without the consulting of the button press.
There has to be a simpler solution. Also this may not be PEP 8 or whatever please be patient because I'm new.
import tkinter as tk
from tkinter import Tk, Label, Button
import sys
import time
import random
import threading
from tkinter import *
window = tk.Tk()
window.geometry("300x300")
window.title("GUI")
def start_screen():
reset()
start = tk.Label(window, text="start of game")
start.place(x=110,y=20)
play = Button(window, text= "play", command = start_game)
play.place(x=110,y=50)
helper = Button(window, text="help", command = help_screen)
helper.place(x=110,y=70)
def stuff():
global t
t = True
print(t)
return t
def text_handling():
global t
t = False
reset()#clears the screen
label = Label(window, text='')
question1= "what is your name?"
label.pack()
print_slow(label, question1, 40)#prints out letters slowly
#here is the part I'm having problems with
name = Entry(window)
name.pack()
but = Button(window, text="enter", command= stuff)
but.pack()
print(t)
if t == True:
myPlayer.name = name.get()
print(myPlayer.name)
def start_game():
reset()
bt = tk.Button(window,text="Enter", bg="orange", command =
text_handling)
bt.place(x=100,y=100)
start_screen()
I am new to programming and Tkinter. I want to DISABLED textbox when checkbox is pressed and open it NORMAL when box is not ticked. Here is my code:
from tkinter import *
root = Tk()
def lock_fields():
if check == True:
data.configure(state=DISABLED)
if check == False:
data.configure(state=NORMAL)
check = BooleanVar()
open_for_edit = Checkbutton(root, text="check the box for editing", variable=check,
onvalue=True, offvalue=False, command=lambda: lock_fields())
open_for_edit.pack()
check = check.get()
data = Text(root)
data.insert(END, "I would like to be able to edit this text only when checkbox is checked.")
data.pack()
root.mainloop()
It seems that for some reason the check-variable is always False when it enters to lock_fields function. I tried passing check argument to the method.
You're pretty close, only thing is that the check.get() line must be in the function. Also you don't need the lambda. Try this:
from tkinter import *
root = Tk()
def lock_fields():
if check.get():
data.configure(state=DISABLED)
else:
data.configure(state=NORMAL)
check = BooleanVar()
open_for_edit = Checkbutton(root, text="check the box for editing", variable=check, onvalue=True, offvalue=False, command=lock_fields)
open_for_edit.pack()
data = Text(root)
data.insert(END, "I would like to be able to edit this text only when checkbox is checked.")
data.pack()
root.mainloop()
Im making a program that searches a website for a specific word.
Exampel : Word: football on the website fifa.com.
I made it in a terminal which was very easy. Now i want to make a program using tkinter and it wont work.
The problem i have is when i run my program it says
File "c:/Users/Censored/Desktop/PythonFolder/Program.py", line 22, in
temp = Button(root, text='GO', command=searchgo)
NameError: name 'searchgo' is not defined
This is my code:
import requests
import re
from tkinter import *
root = Tk()
root.title('WordCounter')
root.configure(bg='#2f3136')
root.geometry('700x700')
root.resizable(False, False)
# Buttons
e1 = Entry(root, width='35')
label1 = Label(root, text='Write The Word You Want To Search For', bg='#2f3136', fg='white',)
e2 = Entry(root, width='35')
label2 = Label(root, text='Write the websites URL', bg='#2f3136', fg='white',)
temp = Button(root, text='GO', command=searchgo)
# Buttons on screen
label1.grid(row='1', column='1',padx='10')
e1.grid(row='2', column='1', padx='10')
label2.grid(row='1', column='2', padx='10')
e2.grid(row='2', column='2', padx='10')
temp.pack()
# Define Functions
def searchgo():
word = e1.get()
URL = e2.get()
page = requests.get(URL).text
print(page.find(word))
root.mainloop()
Thanks for helping me!
Your code has couple of bugs,
Define the function searchgo before you assign the callback to your button
In this code, better use grid to place you button instead of place or you get the following error
cannot use geometry manager pack inside . (root) which already has slaves managed by grid
The reason of this error is that, you cannot use pack and grid geometry managers inside the same master window (root in this program). Since you have used grid for most of the widgets, use grid for placing the button also.
Also, in case you are not aware, in grid geometry manager row and column position values start at 0 and not 1
Here is the code:
import requests
import re
from tkinter import *
root = Tk()
root.title('WordCounter')
root.configure(bg='#2f3136')
root.geometry('700x700')
root.resizable(False, False)
# Buttons
e1 = Entry(root, width='35')
label1 = Label(root, text='Write The Word You Want To Search For', bg='#2f3136', fg='white',)
e2 = Entry(root, width='35')
label2 = Label(root, text='Write the websites URL', bg='#2f3136', fg='white',)
# Define Functions
def searchgo():
word = e1.get()
URL = e2.get()
page = requests.get(URL).text
print(page.find(word))
temp = Button(root, text='GO', command=searchgo)
# Buttons on screen
label1.grid(row='0', column='0',padx='10')
e1.grid(row='1', column='0', padx='10')
label2.grid(row='0', column='1', padx='10')
e2.grid(row='1', column='1', padx='10')
# use the grid manager to place your button
temp.grid(row='1', column='2', padx='10')
root.mainloop()
I have tried explaining the changes I made with some theory. I hope you understand!
Should the function be defined before you assigne it as Button attribute?
This will raise same exception:
class A:
def __init__(self, something):
self.something = something
a = A(func)
def func():
return
But, this works as expected:
def func():
return
class A:
def __init__(self, something):
self.something = something
a = A(func)
I'm trying to make a link slicer that automatically slice and copy the sliced output of the link right after I pasted it on txt = Entry(window,width=50) without clicking a button.
When I paste a link something like this: http://url.io/s/1234abcd/?s=https%3A%2F%2Fexample.com%2Fsome_contens%2F then it will become: example.com/some_contents/
Right now the code below is what I use, but I still have to click the "slice" button before "slicing" and "copying" happens.
from tkinter import *
from urllib import parse
from tkinter import Tk
window = Tk()
window.title("Link Slicer")
window.geometry('344x50')
lbl = Label(window, text="Link")
lbl.grid(column=0, row=1)
txt = Entry(window,width=50)
txt.grid(column=0, row=0)
def clicked():
sliced = txt.get()
sliced = parse.unquote(sliced)
lbl.configure(text= sliced[36:])
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append(sliced[36:])
r.update()
btn = Button(window, text="Slice", command=clicked)
btn.grid(column=1, row=0)
window.mainloop()
I made this code below to try to automate "slicing" and "copying" right after I paste the link in the txt = Entry(window,width=50) without clicking a button (which doesn't work):
from tkinter import *
from urllib import parse
from tkinter import Tk
window = Tk()
window.title("Link Slicer")
window.geometry('344x50')
lbl = Label(window, text="Link")
lbl.grid(column=0, row=1)
txt = Entry(window,width=50)
txt.grid(column=0, row=0)
sliced = txt.get() // 1. automatically get what's in txt = Entry(window,width=50)
sliced = parse.unquote(sliced) // 2. auto-slice
r = Tk() }
r.withdraw() }
r.clipboard_clear() } // 3. auto-copy
r.clipboard_append(sliced[36:]). }
r.update() }
window.mainloop()
Since you always want to operate on the clipboard contents there's no need to even paste the clip into the Entry. You can just grab the clip, transform it, and put it back into the clipboard. I've included an Entry to display the result, but that's not really necessary.
import tkinter as tk
from urllib import parse
root = tk.Tk()
root.title("Link Slicer")
root.geometry('344x50')
root.attributes("-topmost", True)
def clicked():
clip = root.clipboard_get()
clip = parse.unquote(clip)[36:]
root.clipboard_clear()
root.clipboard_append(clip)
entry_text.set(clip)
entry_text = tk.StringVar()
txt = tk.Entry(root, textvariable=entry_text, width=50)
txt.pack()
btn = tk.Button(root, text="Slice", command=clicked)
btn.pack()
root.mainloop()
When I copy the sample URL from your question and click the Slice button I get this result displayed in the Entry and copied to the clipboard. Note that I did not paste the URL into the Entry, I just clicked the button.
example.com/some_contens/
I've included root.attributes("-topmost", True) to force the window to stay above other windows, because I think that's convenient for a tool like this.
As I mentioned in the comments, you should not call Tk() more than once because each call starts a new instance of the Tcl interpreter, which can lead to confusing behaviour (and it's a waste of resources).
I just want that when I type my name inside the entry box then appears in another entry with some add text. The idea is type in the entry below and after that it showed in the big entry.I was looking for this solution, but just found place in Label. I don't want in Label. The window is more big, must drag to show the entry. There's is a picture that i use in this script:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
cat = Entry(root)
cat.place(x=48, y=25, width= 350, height=140)
user = Entry(root)
user.place(x=75, y=550)
btn = Button(root, text='START')
btn.place(x=220, y=410)
root.mainloop()
#
Ok, It works the way you told me,thank you!
But now i'm facing another problem.
The problem is when i insert the function of the game in the second window. I tested in one window and it works, but when i place the function in the second window gives an error when i press the "Start" button:
'''user_try = int(txt.get())
NameError: name 'txt' is not defined'''
When i press reset button gives another error:
'''user_try = int(txt.get())
NameError: name 'txt' is not defined'''
So i know that is missing definition, but i don't know how to make a reference for this command that it's in the second window. Like i said running with just one window the program works.
Maybe i should make using class, i don't know, but i wish to make this way that i started. However if there's no other way to do as i'm doing, let's go.
I just simplify the script here, actualy the main script is more bigger, so my idea is when open the program, there is a window and the user read the instructions about the game and proceed open the second window. The window have pictures and some hidden buttons in the next picture, so there will be an interactivity with the environment.
The guess number is just the beggining. After that there will be new challeges.
I'm very excited doing this, but i'm stuck in this point. The part one i finished, the pictures, the hidden buttons it's exacly the way i want, but the challenge stops here in this problem.
from tkinter import *
from PIL import Image, ImageTk, ImageSequence
import random
from tkinter import messagebox
pc = random.randint(1,10)
def reset():
global pc
pc = random.randint(1,10)
cat['text'] = 'Ok! Lets Try Again!'
def openwin2():
win1.withdraw()
win2 = Toplevel()
win2.geometry('350x300+180+100')
win2.title('second window')
txt = Entry(win2)
txt.place(x=10,y=10)
cat = Label(win2,wraplength=300)
cat.place(x=10,y=50)
cat.config(text='Hi! I Am thinking a number between 1 and 10.')
btn = Button(win2,text='start',command=check)
btn.place(x=30, y=150)
btn2 = Button(win2, text='reset', command=reset)
btn2.place(x=110,y=150)
win2.mainloop()
def check():
user_try = int(txt.get())
if user_try < pc:
msg = 'Hmmmm... the number, which I thought of, is greater than this.'
elif user_try > pc:
msg = 'How about trying a smaller number ?!'
elif user_try == pc:
msg = 'Well Done! You guessed! It was %s the number!' % user_try
else:
msg = 'Something Went Wrong...'
cat['text'] = msg
win1 = Tk()
win1.title('First Window')
win1.geometry('350x300')
user = Label(win1,text='first window')
user.place(x=10,y=10)
btn1 = Button(win1,text='Open Window 2', command=openwin2)
btn1.place(x=10,y=50)
win1.mainloop()
There are multiple ways to do this in tkinter, here's a rework of your code using StringVar objects set to the textvariable properties of your Entry objects:
import tkinter as tk
def doit():
out_string.set("Hello " + in_string.get())
root = tk.Tk()
in_string = tk.StringVar()
out_string = tk.StringVar()
cat = tk.Entry(root, textvariable=in_string)
cat.place(x=20, y=25, width=100)
user = tk.Entry(root, textvariable=out_string)
user.place(x=20, y=75)
btn = tk.Button(root, text='START', command=doit)
btn.place(x=20, y=150)
root.mainloop()
Per #Mike-SMT, here's a different approach using Entry.get() and Entry.insert(). It augments the text when the user clicks the button:
import tkinter as tk
def doit():
user.insert(tk.END, cat.get())
root = tk.Tk()
cat = tk.Entry(root)
cat.place(x=20, y=25, width=100)
user = tk.Entry(root)
user.place(x=20, y=75)
user.insert(0, "Hello ")
btn = tk.Button(root, text='START', command=doit)
btn.place(x=20, y=150)
root.mainloop()
However, you'll see that subsequent button clicks keep appending the text. When working with Entry.insert(), you need to work with Entry.delete() and/or other Entry methods to properly manipulate the text.