How can I make it so that when a certain window is active, the resolution is 1440x1080, but if any other window is active the resolution is 1920x1080 in Python?
(the comments are on purpose)
I'm using tkinter and I've tried:
import subprocess
import tkinter as tk
window = tk.Tk()
if tk.ACTIVE('notepad.exe') *res changing command*
else *res changing command*
# def setresEvent(event):
def startwinexpEvent(event):
subprocess.call(['C:\\Users\\VBucks\\Workspaces\\winexp\\winexp.exe'])
#setRes = tk.Button(
# text='Click me!',
# height=28,
# width=32,
# bg='black',
# fg='white',
#)
# setRes.bind('<Button-1>', setresEvent)
#setRes.pack()
startwinExp = tk.Button(
text='Start winexp',
height=28,
width=32,
bg='black',
fg='white',
)
startwinExp.bind('<Button-WinExp>', startwinexpEvent)
startwinExp.pack()
window.mainloop()
Related
I have a bokeh code that I open it with the terminal typing:
bokeh serve --show graph2d.py
how can I make a tkinter open this bokeh.py(graph2d.py)?
Please help with this, I dont find how to make it work.
this is the tkinter:
import tkinter as tk
from tkinter import *
import graph2d
"""import tkinter as Tk
from tkinter import ttk"""
window = Tk()
window.title("Welcome to PokerScatter app")
"""
WINDOW_SIZE = "600x400"
root = tk.Tk()
root.geometry(WINDOW_SIZE)
"""
selected = IntVar()
rad1 = Radiobutton(window,text='2d Scatter', value=1, variable=selected, command=graph2d)
rad2 = Radiobutton(window,text='3d Scatter', value=2, variable=selected)
rad3 = Radiobutton(window,text='Pie Chart', value=3, variable=selected)
rad4 = Radiobutton(window,text='Histogram', value=4, variable=selected)
def clicked():
print("Processing")
btn = Button(window, text="Show", command=clicked)
rad1.grid(column=0, row=0)
rad2.grid(column=2, row=0)
rad3.grid(column=0, row=1)
rad4.grid(column=2, row=1)
btn.grid(column=6, row=0)
window.mainloop()
Can I make a button that is functional yet isn't visible? I've looked into a bunch of Tkinter threads, but when I tested the codes, they all led to the button completely disappearing and being disabled. Here is what I've got so far:
import tkinter as tk
import time
app=tk.Tk()
app.minsize(500, 500)
#button function
def move():
button.config(state='disabled')
for i in range(50):
frame.place(x=250+i)
frame.update()
time.sleep(0.01)
frame.place(x=250, y=250)
button.config(state='normal')
block=tk.Frame(app, height=50, width=50, bg='red')
frame=tk.Frame(app, height=400, width=400, bg='blue')
#button I wish to be invisible
button=tk.Button(app, text='clickme', command=move)
button.place(x=40, y=40)
frame.place(x=250, y=250, anchor='center')
block.place(x=50, y=50)
app.mainloop()
No, you cannot make an invisible button in tkinter. It must be on the screen for the user to be able to click it.
You can, however, react to clicks anywhere in the window without the need to create a button.
You can set buttons bg and fg same as the frame/root color and set borderwidth=0. This will create a invisible button.
For example refer this
from tkinter import *
root = Tk()
masterFrame = Frame(root, bg='orange', height=300, width=600)
masterFrame.grid(row=0, column=0, sticky='nsew')
Button(masterFrame, text="Invisible button", bg='orange', fg='orange', borderwidth=0).pack()
root.mainloop()
There's a little more to it than just seting the fg and bg, but yeah it can be done.
#! /usr/bin/env python3
from tkinter import *
color = 'SlateGray4'
width, height = 300, 150
desiredX, desiredY = width *0.5, height *0.75
root = Tk() ; root .title( 'Snozberries' )
root .geometry( f'{width}x{height}' )
root .bind( '<Escape>', lambda e: root .destroy() )
root .configure( bg = color )
def one(): ## takes many parameters during construction
print( 'Found a button!' )
def two( event ):
## print( f'x: {event .x}, y: {event.y}' )
if event .x >= desiredX -25 and event .x <= desiredX +25 \
and event .y >= desiredY -25 and event .y <= desiredY +25:
print( 'Found another button!' )
Label( root, bg=color, text='We are the musicmakers,' ) .pack()
Label( root, bg=color, text='and we are the dreamers of the dreams.' ) .pack()
Button( root, bg=color, fg=color, activebackground=color, activeforeground=color,
highlightbackground=color, borderwidth=0, command=one ) .pack()
Label( root, bg=color, text='Button, button' ) .pack()
Label( root, bg=color, text="who's got the button?" ) .pack()
root .bind( '<Button-1>', two )
root .mainloop()
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Tic Tac Toe")
root.geometry("505x500")
root.resizable(0,0)
Blank = tk.PhotoImage(file='Blank.png')
X = tk.PhotoImage(file='X.png')
O = tk.PhotoImage(file='O.png')
def configB(event):
print('hello')
btn1 = tk.Button(root,image=Blank)
btn1.place(x=0,y=0)
btn2 = ttk.Button(image=Blank)
btn2.place(x=165,y=0)
btn3 = ttk.Button(image=Blank)
btn3.place(x=330,y=0)
btn4 = ttk.Button(image=Blank)
btn4.place(x=0,y=165)
btn5 = ttk.Button(image=Blank)
btn5.place(x=165,y=165)
btn6 = ttk.Button(image=Blank)
btn6.place(x=330,y=165)
btn7 = ttk.Button(image=Blank)
btn7.place(x=0,y=330)
btn8 = ttk.Button(image=Blank)
btn8.place(x=165,y=330)
btn9 = ttk.Button(image=Blank)
btn9.place(x=330,y=330)
btn1.bind('<Return>',configB)
root.mainloop()
i want to bind btn1 and i want it to work when i press enter but nothing happens when i press enter as per my code it should print hello .
please help thanks in advance.
As #jasonharper said it will work only if button is focused
btn1.focus()
btn1.bind('<Return>', configB)
and if you click other button then it will not work again
so better bind to main winodw
root.bind('<Return>', configB)
Minimal working code
import tkinter as tk
# --- functions --- # PEP8: lower_case_names
def config_b(event):
print('hello')
# --- main ---
root = tk.Tk()
btn1 = tk.Button(root, text='1')
btn1.pack()
btn1 = tk.Button(root, text='2')
btn1.pack()
#btn1.focus()
#btn1.bind('<Return>', config_b)
root.bind('<Return>', config_b)
root.mainloop()
There is no quick answer to this question.
Buttons must be bound so as to duplicate (as close as possible) normal button behaviour.
This includes changing button relief and colors, then restoring button.
Finally it has to execute the button command.
The following example does this for two buttons.
'button' responds to Mouse 'Button-3'
'buttonX' responds to Key 'Return'
import tkinter as tk
def working():
print("Working...")
def actionPress(event):
event.widget.config(
relief = "sunken",
background = "red",
foreground = "yellow")
def actionRelease(event):
event.widget.config(
relief = "raised",
background = "SystemButtonFace",
foreground = "SystemButtonText")
# activate buttons' command on release
event.widget.invoke()
window = tk.Tk()
button = tk.Button(window, text = "press", command = working)
button.pack()
buttonX = tk.Button(window, text = "pressX", command = working)
buttonX.pack()
# bind returns unique ID
boundP = button.bind("<ButtonPress-3>", actionPress)
boundR = button.bind("<ButtonRelease-3>", actionRelease)
boundXP = buttonX.bind("<KeyPress-Return>", actionPress)
boundXR = buttonX.bind("<KeyRelease-Return>", actionRelease)
# This is how to unbind (if necessary)
# button.unbind(""<ButtonPress-3>", boundP)
# button.unbind(""<ButtonRelease-3>", boundR)
# buttonX.unbind(""<KeyPress-Return>", boundXP)
# buttonX.unbind(""<KeyRelease-Return>", boundXR)
window.mainloop()
You don't need parameter in configB method. Also don't need bind for button1. I also add command in button1 widget. Comment out in line 36 #btn1.bind('<Return>',configB)
def configB():
print('hello')
btn1 = tk.Button(root, command=configB)
Result:
Btw, I don't have png image.
I have an application where I need to know the parameters (font used: Arial, Calibri, etc..., size, color: foreground I believe in tkinter, effect: normal, bold, italic, etc..) of the default font TkDefaultFont used by my widgets.
Today I don't even know what color (foreground in tkinter) to go back to after I change it, since I have no way to "read" the present parameter settings.
I have an Entry widget and will validate the input. If the input is invalid, I will change the color (foreground) to red.
The code below tells you what I have done, what I know and don't know.
from tkinter import *
from tkinter import ttk
import tkinter.font as tkFont
def JMCheckButton2Command(*args):
if JMCheckButton2Variable.get()==1:
JMEntry.config(foreground = 'red')
else:
JMEntry.config(foreground = 'black')
####################### Tk() #######################
JMWindow = Tk()
s=ttk.Style()
print('\nTheme names are ', s.theme_names())
print('\nLayout of style TButton is:\n', s.layout('TButton'))
print('\nLayout of style TEntry is:\n', s.layout('TEntry'))
print("\nOptions available for element 'Button.label':\n",
s.element_options('Button.label'))
print("\nOptions available for element 'Entry.textarea':\n",
s.element_options('Entry.textarea'))
print("\nFont used in style 'TButton': ", s.lookup('TButton', 'font'))
print("\nFont used in style 'TButton': ", s.lookup('TEntry', 'font'))
####################### ttk.Frame #######################
JMFrame2=ttk.Frame(JMWindow, width='1i', height='2i', borderwidth='5',
relief='raised', padding=(5,5))
JMFrame2.grid()
####################### ttk.Entry #######################
JMEntryVariable = StringVar()
JMEntry = ttk.Entry(JMFrame2, textvariable=JMEntryVariable, width = 25)
JMEntry.insert(0, '100') # insert new text at a given index
####################### ttk.Label #######################
JMLabel2Text2Display = StringVar()
JMLabel2Text2Display.set('Enter number: ')
JMLabel2 = ttk.Label(JMFrame2, textvariable = JMLabel2Text2Display,
justify = 'center')
####################### ttk.Checkbutton #######################
JMCheckButton2Variable = IntVar()
JMCheckButton2=ttk.Checkbutton(JMFrame2, text='Change font color',
command = JMCheckButton2Command, variable = JMCheckButton2Variable)
JMLabel2.grid(column=0, row=0)
JMEntry.grid(column=1, row=0)
JMCheckButton2.grid(column=2, row=0, sticky = 'w', padx=25)
JMWindow.mainloop()
In general, Tk options/properties can be set #construction,
or later with calls to configure() / config().
What can be set with config(), can be queried with cget().
Can also index widgets with option names: widget['option']).
See tkinter sources, e.g. under: /usr/lib/python3.6/tkinter/
And Tcl/Tk documentation:
https://www.tcl.tk/man/tcl/TkCmd/contents.htm
For available options, you can search under:
https://www.tcl.tk/man/tcl/TkCmd/options.htm
and within:
/usr/lib/python3.6/tkinter/__init__.py
E.g. if you wanted to see options supported by class Button:
https://www.tcl.tk/man/tcl/TkCmd/button.htm
and within tkinter/__init__.py:
class Button(Widget):
"""Button widget."""
def __init__(self, master=None, cnf={}, **kw):
"""Construct a button widget with the parent MASTER.
STANDARD OPTIONS
activebackground, activeforeground, anchor,
...
import tkinter as tk
root = tk.Tk()
l = tk.Label(
root, text='asdf', font=('Times', 20)
)
l.pack()
tk.Button(
text='query font',
command=lambda: print(l.cget('font'))
).pack()
tk.Button(
text='change font',
command=lambda: l.configure(font=('Courier', 12))
).pack()
tk.Button(
text='query foreground',
command=lambda: print(l.cget('foreground'))
).pack()
tk.Button(
text='change foreground',
command=lambda: l.configure(foreground='#FF0000')
).pack()
root.mainloop()
Another example (different ways to get/set Tk options):
(See /usr/lib/python3.6/tkinter/font.py (has examples #end))
import tkinter as tk
from tkinter.font import Font # Access Font class directly.
from tkinter import font # To access 'weight' (BOLD etc.).
root = tk.Tk()
# printing f1 (without calling actual()) will print its name
f1 = Font(family='times', size=30, weight=font.NORMAL)
# printing f2 will print the tuple values
f2 = ('courier', 18, 'bold') # Can also use plain tuples.
# This will inlcude name for f1 (created with Font class),
# but not for f2 (f2 is just a tuple).
print('Names of currently available fonts:')
for fName in font.names(): print(fName)
label = tk.Label(root, text='Label Text', font=f1)
label.pack()
tk.Button(
text='Change font (config())',
command=lambda: label.config(font=f1)
).pack()
# Note: cannot use assignment inside lambda,
# so using ordinary function as callback here.
def changeFontWithMapNotation(): label['font'] = f2
tk.Button(
text='Change font (index map)',
command=lambda: changeFontWithMapNotation()
).pack()
tk.Button(
text='Read font (cget())',
command=lambda: print('font:', label.cget('font'))
).pack()
tk.Button(
text='Read font (index map)',
command=lambda: print('font:', label['font'])
).pack()
root.mainloop()
After looking around a bit into ttk source:
/usr/lib/python3.6/tkinter/ttk.py
and at the official docs:
https://www.tcl.tk/man/tcl/TkCmd/ttk_intro.htm
https://www.tcl.tk/man/tcl/TkCmd/ttk_style.htm
here is a ttk example, creating & using a minimal custom style:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
styleDb = ttk.Style(root)
csName = 'CustomLabelStyle'
# Need to define layout for custom style, before using it.
# Just copy the corresponding layout from ttk.
csLayout = styleDb.layout('TLabel')
styleDb.layout(csName, csLayout)
# Set ttk options, for custom style, in ttk style database.
styleDb.configure(
csName,
font=('Courier',18),
foreground='#22AA55',
background='#AA5522'
)
# Use custom style for specific widget.
label = ttk.Label(root, text='ttk label', style=csName)
label.pack()
ttk.Button(
root, text='default style',
command=lambda: label.config(style='TLabel')
).pack()
ttk.Button(
root, text='custom style',
command=lambda: label.config(style=csName)
).pack()
defaultLabelFont = styleDb.lookup('TLabel', 'font')
print(defaultLabelFont)
fontVar = tk.StringVar(root, styleDb.lookup(csName, 'font'))
ttk.Entry(root, textvariable=fontVar).pack()
ttk.Button(
root,text='set custom style font',
command=lambda: styleDb.configure(
csName, font=fontVar.get()
)
).pack()
root.mainloop()
I'm currently trying to learn how to build GUIs with tkinter, and I've run into a problem with my test app.
I have a button that displays an image on it instead of text, and I also have a set of radio buttons that I want to control which image is shown on the regular button. Currently the radio buttons don't seem to be updating my photofilepath StringVar as the button always has the default photo, regardless of selected radio button. Here is my (Simplified) code:
root = Tk() # Set up
root.title("Test GUI")
gui.grid(column=0, row=0, sticky=(N, W, E, S))
photofilepath = StringVar() # Set default photo
photofilepath.set("C:/Users/Ben/Pictures/Default photo.png")
photo = PhotoImage(file=photofilepath.get())
CalcButton = ttk.Button(gui, image=photo)
CalcButton.grid(column=3, row=2, columnspan=1)
# Set button photo
Photo1Rbutton = ttk.Radiobutton(gui, text="Photo 1", variable=photofilepath,
value='C:/Users/Ben/Pictures/Photo 1.png')
Photo1Rbutton.grid(column=4, row=2, sticky=S)
Photo2Rbutton = ttk.Radiobutton(gui, text="Photo 2", variable=photofilepath,
value='C:/Users/Ben/Pictures/Photo 2.png')
Photo2Rbutton.grid(column=4, row=3)
root.mainloop()
Thanks in advance for any help.
You can use command= in Radiobutton to assign function which will load new image and put them in label.
Working example (you have to only set paths)
import tkinter as tk
from tkinter import ttk
# to easily change example
DEFAULT = "C:/Users/Ben/Pictures/Default photo.png"
PHOTO_1 = "C:/Users/Ben/Pictures/Photo 1.png"
PHOTO_2 = "C:/Users/Ben/Pictures/Photo 2.png"
def change_image():
print(photo_filepath.get())
photo = tk.PhotoImage(file=photo_filepath.get())
calc_button['image'] = photo
calc_button.image = photo # solution for garbage-collector problem. you have to assign PhotoImage object to global variable or class variable
# - or -
photo['file'] = photo_filepath.get()
calc_button['image'] = photo
root = tk.Tk() # Set up
root.title("Test GUI")
photo_filepath = tk.StringVar() # Set default photo
photo_filepath.set(DEFAULT)
photo = tk.PhotoImage(file=photo_filepath.get())
calc_button = ttk.Button(root, image=photo)
calc_button.grid(column=3, row=2, columnspan=1)
photo1_radiobutton = ttk.Radiobutton(root, text="Photo 1", variable=photo_filepath,
value=PHOTO_1, command=change_image)
photo1_radiobutton.grid(column=4, row=2, sticky=tk.S)
photo2_radiobutton = ttk.Radiobutton(root, text="Photo 2", variable=photo_filepath,
value=PHOTO_2, command=change_image)
photo2_radiobutton.grid(column=4, row=3)
root.mainloop()