Tester un code sur Mac

Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024 - Modifié le 1 juin 2023 à 14:09
 jilo - 9 juin 2023 à 08:59

Bonjour,

Y aurait-il une bonne âme assez sympathique et possédant un Mac pour tester le code suivant ?

(je suis sur Windows et n'ai pas de Mac sous la main ...)

Lancer le truc et appuyer juste sur entrée (pas besoin de remplir les champs)

Merci d'avance

# -*- coding:Utf-8 -*-

from math import *
from tkinter import *
from tkinter import messagebox

def calculation(evt):

	graph_area.create_rectangle(100,100,300,300, fill = 'orange')

def update_scale():

	e6.delete(0,END)
	e7.delete(0,END)
	e8.delete(0,END)
	e9.delete(0,END)

	if(rbvar.get() == 1):
		e6.insert(0,'4')
		e7.insert(0,'4')
		e8.insert(0,'2')
		e9.insert(0,'2')
	else:
		e6.insert(0,'0.04')
		e7.insert(0,'0.04')
		e8.insert(0,'0.02')
		e9.insert(0,'0.02')


bg_color = 'lightsteelblue'
WIDTH, HEIGHT = 1000, 505

main_win = Tk()
main_win.geometry(str(WIDTH)+'x'+str(HEIGHT)+'+200+50')
main_win.title('Test')
main_win.configure(background = bg_color)

graph_area = Canvas(main_win, width = WIDTH-20, height = HEIGHT-155, bg = 'ivory')
graph_area.place(x=10, y = 10)

f1 = LabelFrame(main_win, width = 440, height = 50, bd = 2, relief = GROOVE, text = 'F1 ')
f1.configure(background = bg_color)
f1.place(x = 10,y = 390)

Label(f1, bg = bg_color, text = 'p1').place(x=5, y=4)
e1 = Entry(f1, width = 5)
e1.place(x = 65,y = 4)
e1.bind("<Return>", calculation)
e1.focus()

Label(f1, bg = bg_color, text = 'p2').place(x=110, y=4)
e2 = Entry(f1, width = 5)
e2.place(x = 210,y = 4)
e2.bind("<Return>", calculation)

Label(f1, bg = bg_color, text = 'p3').place(x=254, y=4)
e3 = Entry(f1, width = 5)
e3.place(x = 366,y = 4)
e3.insert(0,'0.0')
e3.bind("<Return>", calculation)

f2 = LabelFrame(main_win, width = 760, height = 50, bd = 2, relief = GROOVE, text = 'F2 ')
f2.configure(background = bg_color)
f2.place(x = 10,y = 445)

Label(f2, bg = bg_color, text = 'p4').place(x=5, y=4)
e4= Entry(f2, width = 5)
e4.place(x = 65,y = 4)
e4.bind("<Return>", calculation)

Label(f2, bg = bg_color, text = 'p5').place(x=110, y=4)
e5 = Entry(f2, width = 5)
e5.place(x = 163,y = 4)
e5.bind("<Return>", calculation)

Label(f2, bg = bg_color, text = 'p6').place(x=216, y=4)
e6 = Entry(f2, width = 5)
e6.place(x = 286,y = 4)
e6.insert(0,'4')
e6.bind("<Return>", calculation)

Label(f2, bg = bg_color, text = 'p7').place(x=339, y=4)
e7 = Entry(f2, width = 5)
e7.place(x = 409,y = 4)
e7.insert(0,'4')
e7.bind("<Return>", calculation)

Label(f2, bg = bg_color, text = 'p8').place(x=462, y=4)
e8 = Entry(f2, width = 5)
e8.place(x = 532,y = 4)
e8.insert(0,'2')
e8.bind("<Return>", calculation)

Label(f2, bg = bg_color, text = 'p9').place(x=585, y=4)
e9 = Entry(f2, width = 5)
e9.place(x = 655,y = 4)
e9.insert(0,'2')
e9.bind("<Return>", calculation)

f3 = Frame(main_win, width = 310, height = 43, bd = 2, relief = GROOVE)
f3.configure(background = bg_color)
f3.place(x = 460,y = 398)

rbvar1 = IntVar()
rb3 = Radiobutton(f3, text="p10", variable=rbvar1, value=3, bg = bg_color)
rb3.place(x = 4,y = 7)
rb3.select()

rb4 = Radiobutton(f3, text="p11", variable=rbvar1, value=4, bg = bg_color)
rb4.place(x = 170,y = 7)

f4 = Frame(main_win, width = 200, height = 97, bd = 2, relief = GROOVE)
f4.configure(background = bg_color)
f4.place(x = 780,y = 398)

rbvar = IntVar()
rb1 = Radiobutton(f4, text="Mesures en centimètres", variable=rbvar, value=1, bg = bg_color ,command = update_scale)
rb1.place(x = 4,y = 7)
rb1.select()

rb2 = Radiobutton(f4, text="Mesures en mètres", variable=rbvar, value=2, bg = bg_color, command = update_scale)
rb2.place(x = 4,y = 60)

main_win.mainloop()


Windows / Edge 113.0.1774.57

A voir également:

10 réponses

Bonsoir.

Utiliser des "place" conduit inoxérablement à avoir ce genre de souci, ce n'est pas viable, tkinter fournit 2 gestionnaires de placement : pack et grid, dont il faut certes comprendre le fonctionnement, grid est sans doute plus simple à comprendre, c'est similaire aux tableaux html, et le gros avantage de pack et grid est qu'ils s'étirent en fonction du redimensionnement de la fenêtre, l'extensibilité est quand même un gros point positif, on pourrait comparer place à une position absolue en css, et pack, grid à des positions relatives ^^

En partant de ton code en utilisant grid

import tkinter as tk

BG_COLOR = 'lightsteelblue'
GRAPH_AREA_WIDTH = 980
GRAPH_AREA_HEIGHT = 350
GRAPH_AREA_BG = 'ivory'


def calculation(evt):
    graph_area.create_rectangle(100, 100, 300, 300, fill='orange')


def update_scale():
    for i in range(6, 10):
        entries[f'p{i}'].delete(0, tk.END)
    if main_win.getvar(name='mesure') == 1:
        values = 4, 2
    else:
        values = 0.04, 0.02  # ? intvar et non doublevar
    for i in range(6, 8):
        entries[f'p{i}'].insert(0, values[0])
    for i in range(8, 10):
        entries[f'p{i}'].insert(0, values[1])


main_win = tk.Tk()
main_win.title('Test')
main_win.config(bg=BG_COLOR, padx=10, pady=10)

main_win.columnconfigure(0, weight=1)
main_win.columnconfigure(1, weight=1)
main_win.columnconfigure(2, weight=0)

graph_area = tk.Canvas(
    main_win, width=GRAPH_AREA_WIDTH, height=GRAPH_AREA_HEIGHT, bg=GRAPH_AREA_BG
)
graph_area.grid(row=0, column=0, columnspan=3, pady=(0, 15))

entries = {}

area_1 = tk.LabelFrame(
    main_win, text=' F1 ', bg=BG_COLOR, fg='#000', bd=2, relief=tk.GROOVE
)
area_1.grid(row=1, column=0, padx=5, ipady=5, sticky=tk.EW)

for col, text in enumerate(('p1', 'p2', 'p3')):
    area_1.columnconfigure(col, weight=1)
    frame = tk.Frame(area_1)
    frame.grid(row=0, column=col)
    label = tk.Label(frame, bg=BG_COLOR, text=text)
    label.grid()
    entry = tk.Entry(frame, width=5)
    entry.grid(row=0, column=1)
    entry.bind('<Return>', calculation)
    entries[text] = entry

area_2 = tk.LabelFrame(main_win, bg=BG_COLOR, fg='#000', bd=2, relief=tk.GROOVE)
area_2.grid(row=1, column=1, padx=5, ipady=5, sticky=tk.EW)
area_2.rowconfigure(0, weight=1)

int_var = tk.IntVar(name='pn')
for col, (text, value) in enumerate((('p10', 3), ('p11', 4))):
    area_2.columnconfigure(col, weight=1)
    rbutton = tk.Radiobutton(
        area_2, text=text, variable=int_var, value=value, bg=BG_COLOR
    )
    rbutton.grid(row=0, column=col)
    if col == 0:
        rbutton.select()

area_3 = tk.LabelFrame(main_win, bg=BG_COLOR, fg='#000', bd=2, relief=tk.GROOVE)
area_3.grid(row=1, column=2, rowspan=2, padx=5, ipady=5, sticky=tk.NSEW)

int_var = tk.IntVar(name='mesure')
for row, (text, value) in enumerate((('centimètres', 1), ('mètres', 2))):
    rbutton = tk.Radiobutton(
        area_3,
        text=f"Mesures en {text}",
        variable=int_var,
        value=value,
        bg=BG_COLOR,
        command=update_scale,
    )
    rbutton.grid(row=row, column=0, sticky=tk.W, padx=10, pady=10)
    if row == 0:
        rbutton.select()


area_4 = tk.LabelFrame(
    main_win, text=' F2 ', bg=BG_COLOR, fg='#000', bd=2, relief=tk.GROOVE
)
area_4.grid(row=2, column=0, columnspan=2, padx=5, ipady=5, sticky=tk.EW)

for col, (text, value) in enumerate(
    ((4, ''), (5, ''), (6, '4'), (7, '4'), (8, '2'), (9, '2'))
):
    area_4.columnconfigure(col, weight=1)
    frame = tk.Frame(area_4)
    frame.grid(row=0, column=col)
    label = tk.Label(frame, bg=BG_COLOR, text=f'p{text}')
    label.grid()
    entry = tk.Entry(frame, width=5, text=value)
    entry.grid(row=0, column=1)
    entry.bind('<Return>', calculation)
    entries[f'p{text}'] = entry


main_win.mainloop()
1
Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024 178
4 juin 2023 à 19:14

Bonjour Plochu,

J'ai testé ton code:

1_ on voit des défauts d'alignement

2_ les radio button se comportent de façon bizarre, au lancement du programme, aucun n'est sélectionné

puis, en survolant le bouton p11 avec la souris (donc sans cliquer), p11 se sélectionne puis p10

et donc les 2 sont sélectionnés en même temps:

0
plochu > Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024
5 juin 2023 à 12:07

Salut Phil_1857.

Oui, le problème des radios vient uniquement du nom des Intvar, en les nommant différemment, c'est réglé.

En revanche, le décalage est un peu normal puisque d'un côté il y a un titre et des autres il n'y en a pas, ce qui fait que logiquement l'alignement n'est plus correct.


Pour contrebalancer ce décalage, il faudrait connaître la dimension du texte, on peut le récupérer en récupérant la métrique de la police, mais il y a toujours un léger décalage, à voir si ça fonctionne mieux sur Windows que sur Linux.

Par exemple avec area1

import tkinter
from tkinter import font


# ...


area_1 = tk.LabelFrame(
    main_win, labelwidget=frame_title, bg=BG_COLOR, bd=2, relief=tk.GROOVE
)
area_1.grid(row=1, column=0, padx=5, ipady=5, sticky=tk.NSEW)
font_height = font.Font(font=area_1['font']).metrics('linespace')

Mais il manque quelques pixels, je ne sais comment sont construits les labelframes, sans doute que ce sont des labels.

Donc au lieu de texte, on peut utiliser ses propres labels et récupérer la hauteur pour ajuster les alignements à peu près correctement.

import tkinter as tk
from tkinter import font as tk_font

BG_COLOR = 'lightsteelblue'
GRAPH_AREA_WIDTH = 980
GRAPH_AREA_HEIGHT = 350
GRAPH_AREA_BG = 'ivory'


def calculation(evt):
    graph_area.create_rectangle(100, 100, 300, 300, fill='orange')


def update_scale():
    for i in range(6, 10):
        entries[f'p{i}'].delete(0, tk.END)
    if main_win.getvar(name='mesure') == 1:
        values = 4, 2
    else:
        values = 0.04, 0.02  # ? intvar et non doublevar
    for i in range(6, 8):
        entries[f'p{i}'].insert(0, values[0])
    for i in range(8, 10):
        entries[f'p{i}'].insert(0, values[1])


main_win = tk.Tk()
main_win.title('Test')
main_win.config(bg=BG_COLOR, padx=10, pady=10)

# Police des titres de labelframes
frame_title_font = tk_font.Font(main_win, family='serif', size=-12)

main_win.columnconfigure(0, weight=1)
main_win.columnconfigure(1, weight=1)
main_win.columnconfigure(2, weight=0)

graph_area = tk.Canvas(
    main_win, width=GRAPH_AREA_WIDTH, height=GRAPH_AREA_HEIGHT, bg=GRAPH_AREA_BG
)
graph_area.grid(row=0, column=0, columnspan=3, pady=(0, 15))

entries = {}

# Utilisation d'un label à la place d'un simple text pour le labelframe
# afin de pouvoir déterminer la hauteur du texte et s'en servir pour décaler
# les labelframes sans titre.
frame_title = tk.Label(
    main_win, text='F1', font=frame_title_font, bg=BG_COLOR, fg='#000', padx=5
)

frame_title_height = frame_title.winfo_reqheight()
area_1 = tk.LabelFrame(
    # donc plus de text mais le label
    main_win,
    labelwidget=frame_title,
    bg=BG_COLOR,
    bd=2,
    relief=tk.GROOVE,
)
area_1.grid(row=1, column=0, padx=5, ipady=5, sticky=tk.NSEW)

for col, text in enumerate(('p1', 'p2', 'p3')):
    area_1.columnconfigure(col, weight=1)
    frame = tk.Frame(area_1)
    frame.grid(row=0, column=col)
    label = tk.Label(frame, bg=BG_COLOR, fg='#000', text=text)
    label.grid(sticky=tk.NS, ipadx=10)
    entry = tk.Entry(frame, width=5)
    entry.grid(row=0, column=1)
    entry.bind('<Return>', calculation)
    entries[text] = entry


area_2 = tk.LabelFrame(main_win, bg=BG_COLOR, fg='#000', bd=2, relief=tk.GROOVE)
# Décalage vers le bas de la moitié de la hauteur du text du titre des labels via le pady
area_2.grid(
    row=1, column=1, padx=5, pady=(frame_title_height // 2, 0), ipady=5, sticky=tk.NSEW
)
area_2.rowconfigure(0, weight=1)

int_var_pn = tk.IntVar(name='pn')
for col, (text, value) in enumerate((('p10', 3), ('p11', 4))):
    area_2.columnconfigure(col, weight=1)
    rbutton = tk.Radiobutton(
        area_2,
        text=text,
        variable=int_var_pn,
        value=value,
        bg=BG_COLOR,
        selectcolor='#000',
    )
    rbutton.grid(row=0, column=col)
    if col == 0:
        rbutton.select()

area_3 = tk.LabelFrame(main_win, bg=BG_COLOR, fg='#000', bd=2, relief=tk.GROOVE)
# Idem, décalage puisque sans titre
area_3.grid(
    row=1,
    column=2,
    rowspan=2,
    padx=5,
    pady=(frame_title_height // 2, 0),
    ipady=5,
    sticky=tk.NSEW,
)

int_var_mes = tk.IntVar(name='mesure')
for row, (text, value) in enumerate((('centimètres', 1), ('mètres', 2))):
    rbutton = tk.Radiobutton(
        area_3,
        text=f"Mesures en {text}",
        variable=int_var_mes,
        value=value,
        bg=BG_COLOR,
        selectcolor='#000',
        command=update_scale,
    )
    rbutton.grid(row=row, column=0, sticky=tk.W, padx=10, pady=10)
    if row == 0:
        rbutton.select()

frame_title = tk.Label(
    main_win, text='F2', font=frame_title_font, bg=BG_COLOR, fg='#000', padx=5,
)
area_4 = tk.LabelFrame(
    main_win, labelwidget=frame_title, bg=BG_COLOR, fg='#000', bd=2, relief=tk.GROOVE
)
area_4.grid(row=2, column=0, columnspan=2, padx=5, pady=(10, 0), ipady=5, sticky=tk.EW)

for col, (text, value) in enumerate(
    ((4, ''), (5, ''), (6, '4'), (7, '4'), (8, '2'), (9, '2'))
):
    area_4.columnconfigure(col, weight=1)
    frame = tk.Frame(area_4)
    frame.grid(row=0, column=col)
    label = tk.Label(frame, text=f'p{text}', bg=BG_COLOR, fg='#000')
    label.grid(sticky=tk.NS, ipadx=10)
    entry = tk.Entry(frame, width=5, text=value)
    entry.grid(row=0, column=1)
    entry.bind('<Return>', calculation)
    entries[f'p{text}'] = entry


main_win.mainloop()

A voir ce que cela donne sur Windows ( et autres systèmes), mais pas de raison que cela diffère de chez moi qui suis sur Debian et mate.

Il est préférable de définir la couleur des indicator, car par ex. chez moi, je ne vois pas les radios en sélection si la couleur n'est pas définie, en fait ... il vaut mieux définir toutes les couleurs, car, selon les thèmes graphiques, certains éléments peuvent rester invisibles, enfin cela dépend si on veut une compatibilité multi-systèmes.

L'idéal serait d'utiliser des classes pour clarifier ce code un peu brouillon, mais qui n'était qu'un exemple de l'utilisation de grid.

0
Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024 178 > plochu
5 juin 2023 à 13:23

Bonjour,

Au lancement du code, sans rien toucher on à ceci:

Ca va mieux si on enlève l'option selectcolor dans la définition des radio button

0
Diablo76 Messages postés 161 Date d'inscription vendredi 25 novembre 2022 Statut Membre Dernière intervention 1 mai 2024 41 > Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024
Modifié le 5 juin 2023 à 13:51

Salut,

Je n'ai pas ce phénomène de radio button sur Windows 10 avec le code de @plochu

Edit: oui ils s'activent quand on les survole....

Par contre sur Mac OS, j'ai un problème sur le background color sur les labels :

0
plochu > Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024
5 juin 2023 à 15:36

C'est pour ça que je disais qu'il vaut mieux définir toutes les options de couleurs ^^
Au moins plus de problème d'invisibilité, et surtout d'uniformisation peu importe le système utilisé.


Par exemple en créant sa propre classe héritant de tk.Radiobutton avec des options définies.


 

class RadioButton(tk.Radiobutton):
    def __init__(self, *args, **kw):
        options = dict(
            activebackground='navy', # survol souris
            activeforeground=BG_COLOR, # survol souris
            background=BG_COLOR,
            foreground='navy',
            disabledforeground='grey', # lorsque state=tk.DISABLED
            highlightbackground=BG_COLOR, # sans focus (via touche tab)
            highlightcolor='navy', # en focus (via touche tab)
            selectcolor='white',
            borderwidth=0,
        )
        # voir s'il est autorisé d'outrepasser les options prédéfinies,
        # en ce cas faire options.update(kw) à la place et passer options
        # dans super au lieu de kw...
        kw.update(options)
        super().__init__(*args, kw)
0
Diablo76 Messages postés 161 Date d'inscription vendredi 25 novembre 2022 Statut Membre Dernière intervention 1 mai 2024 41
1 juin 2023 à 15:57

Salut,

Voilà ce que ça donne:

0
Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024 178
Modifié le 1 juin 2023 à 17:02

Merci Diablo,

Ca marche, le seul problème est que les labels empiètent sur les entries: regarde p2, par exemple

en fait les boites des entries ont l'air plus grandes, on voit que le bas touche le cadre de F1

Sur Windows, on à ça:

Tu vois une solution ?

Comment adapter le code pour que ce soit ok sur les 2 OS ?

0
Diablo76 Messages postés 161 Date d'inscription vendredi 25 novembre 2022 Statut Membre Dernière intervention 1 mai 2024 41
Modifié le 1 juin 2023 à 18:29

Avec Tkinter c'est un peu le bordel...

Il faut jouer sur les décalages

et le code (j'ai ajouté une fonction get_os())

# -*- coding:Utf-8 -*-
import sys
from math import *
from tkinter import *
from tkinter import messagebox


def calculation(evt):
    graph_area.create_rectangle(100, 100, 300, 300, fill="orange")


def update_scale():
    e6.delete(0, END)
    e7.delete(0, END)
    e8.delete(0, END)
    e9.delete(0, END)

    if rbvar.get() == 1:
        e6.insert(0, "4")
        e7.insert(0, "4")
        e8.insert(0, "2")
        e9.insert(0, "2")
    else:
        e6.insert(0, "0.04")
        e7.insert(0, "0.04")
        e8.insert(0, "0.02")
        e9.insert(0, "0.02")


def get_os():
    if sys.platform == "darwin":
        return 20, -4, -7
    else:
        return 0, 0, 0


bg_color = "lightsteelblue"
WIDTH, HEIGHT = 1000, 505


offset_label_x, offset_label_y, offset_entry = get_os()


main_win = Tk()
main_win.geometry(str(WIDTH) + "x" + str(HEIGHT) + "+200+50")
main_win.title("Test")
main_win.configure(background=bg_color)

graph_area = Canvas(main_win, width=WIDTH - 20, height=HEIGHT - 155, bg="ivory")
graph_area.place(x=10, y=10)

f1 = LabelFrame(main_win, width=440, height=50, bd=2, relief=GROOVE, text="F1 ")
f1.configure(background=bg_color)
f1.place(x=10, y=390)

Label(f1, bg=bg_color, text="p1").place(x=5, y=4 + offset_label_y)
e1 = Entry(f1, width=5)
e1.place(x=65, y=4 + offset_entry)
e1.bind("<Return>", calculation)
e1.focus()

Label(f1, bg=bg_color, text="p2").place(x=110 + offset_label_x, y=4 + offset_label_y)
e2 = Entry(f1, width=5)
e2.place(x=210, y=4 + offset_entry)
e2.bind("<Return>", calculation)

Label(f1, bg=bg_color, text="p3").place(x=254 + offset_label_x, y=4 + offset_label_y)
e3 = Entry(f1, width=5)
e3.place(x=366, y=4 + offset_entry)
e3.insert(0, "0.0")
e3.bind("<Return>", calculation)

f2 = LabelFrame(main_win, width=760, height=50, bd=2, relief=GROOVE, text="F2 ")
f2.configure(background=bg_color)
f2.place(x=10, y=445)

Label(f2, bg=bg_color, text="p4").place(x=5, y=4 + offset_label_y)
e4 = Entry(f2, width=5)
e4.place(x=65, y=4 + offset_entry)
e4.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="p5").place(x=110 + offset_label_x, y=4 + offset_label_y)
e5 = Entry(f2, width=5)
e5.place(x=163, y=4 + offset_entry)
e5.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="p6").place(x=216 + offset_label_x, y=4 + offset_label_y)
e6 = Entry(f2, width=5)
e6.place(x=286, y=4 + offset_entry)
e6.insert(0, "4")
e6.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="p7").place(x=339 + offset_label_x, y=4 + offset_label_y)
e7 = Entry(f2, width=5)
e7.place(x=409, y=4 + offset_entry)
e7.insert(0, "4")
e7.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="p8").place(x=462 + offset_label_x, y=4 + offset_label_y)
e8 = Entry(f2, width=5)
e8.place(x=532, y=4 + offset_entry)
e8.insert(0, "2")
e8.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="p9").place(x=585 + offset_label_x, y=4 + offset_label_y)
e9 = Entry(f2, width=5)
e9.place(x=655, y=4 + offset_entry)
e9.insert(0, "2")
e9.bind("<Return>", calculation)

f3 = Frame(main_win, width=310, height=43, bd=2, relief=GROOVE)
f3.configure(background=bg_color)
f3.place(x=460, y=398)

rbvar1 = IntVar()
rb3 = Radiobutton(f3, text="p10", variable=rbvar1, value=3, bg=bg_color)
rb3.place(x=4, y=7)
rb3.select()

rb4 = Radiobutton(f3, text="p11", variable=rbvar1, value=4, bg=bg_color)
rb4.place(x=170, y=7)

f4 = Frame(main_win, width=200, height=97, bd=2, relief=GROOVE)
f4.configure(background=bg_color)
f4.place(x=780, y=398)

rbvar = IntVar()
rb1 = Radiobutton(
    f4,
    text="Mesures en centimètres",
    variable=rbvar,
    value=1,
    bg=bg_color,
    command=update_scale,
)
rb1.place(x=4, y=7)
rb1.select()

rb2 = Radiobutton(
    f4,
    text="Mesures en mètres",
    variable=rbvar,
    value=2,
    bg=bg_color,
    command=update_scale,
)
rb2.place(x=4, y=60)

main_win.mainloop()
0
Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024 178
Modifié le 2 juin 2023 à 11:49

Bonjour,

Ok, je vais étudier tout ça en détails

En attendant, Diablo, tu vas dire que je te casse les pieds :-)

mais j'ai été un peu optimiste en simplifiant les textes de mes labels

pourrais-tu re tester avec ce code stp ?

# -*- coding:Utf-8 -*-

import sys
from math import *
from tkinter import *
from tkinter import messagebox

def get_os():
    if sys.platform == 'win32':
        return 0,0,0
    else:
        return 20,-4,-7

def calculation(evt):
    graph_area.create_rectangle(100, 100, 300, 300, fill="orange")

def update_scale():
    e6.delete(0, END)
    e7.delete(0, END)
    e8.delete(0, END)
    e9.delete(0, END)

    if rbvar.get() == 1:
        e6.insert(0, "4")
        e7.insert(0, "4")
        e8.insert(0, "2")
        e9.insert(0, "2")
    else:
        e6.insert(0, "0.04")
        e7.insert(0, "0.04")
        e8.insert(0, "0.02")
        e9.insert(0, "0.02")

bg_color = "lightsteelblue"
WIDTH, HEIGHT = 1000, 505
offset_label_x, offset_label_y, offset_entry = get_os()

main_win = Tk()
main_win.geometry(str(WIDTH) + "x" + str(HEIGHT) + "+200+50")
main_win.title("Test")
main_win.configure(background=bg_color)

graph_area = Canvas(main_win, width=WIDTH - 20, height=HEIGHT - 155, bg="ivory")
graph_area.place(x=10, y=10)

f1 = LabelFrame(main_win, width=440, height=50, bd=2, relief=GROOVE, text="F1 ")
f1.configure(background=bg_color)
f1.place(x=10, y=390)

Label(f1, bg=bg_color, text="Hauteur").place(x=5, y=4 + offset_label_y)
e1 = Entry(f1, width=5)
e1.place(x=65, y=4 + offset_entry)
e1.bind("<Return>", calculation)
e1.focus()

Label(f1, bg=bg_color, text="Longueur pente").place(x=110 + offset_label_x, y=4 + offset_label_y)
e2 = Entry(f1, width=5)
e2.place(x=210, y=4 + offset_entry)
e2.bind("<Return>", calculation)

Label(f1, bg=bg_color, text="Longueur sommet").place(x=254 + offset_label_x, y=4 + offset_label_y)
e3 = Entry(f1, width=5)
e3.place(x=366, y=4 + offset_entry)
e3.insert(0, "0.0")
e3.bind("<Return>", calculation)

f2 = LabelFrame(main_win, width=760, height=50, bd=2, relief=GROOVE, text="F2 ")
f2.configure(background=bg_color)
f2.place(x=10, y=445)

Label(f2, bg=bg_color, text="Longueur").place(x=5, y=4 + offset_label_y)
e4 = Entry(f2, width=5)
e4.place(x=65, y=4 + offset_entry)
e4.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="Largeur").place(x=110 + offset_label_x, y=4 + offset_label_y)
e5 = Entry(f2, width=5)
e5.place(x=163, y=4 + offset_entry)
e5.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="External H").place(x=216 + offset_label_x, y=4 + offset_label_y)
e6 = Entry(f2, width=5)
e6.place(x=286, y=4 + offset_entry)
e6.insert(0, "4")
e6.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="External V").place(x=339 + offset_label_x, y=4 + offset_label_y)
e7 = Entry(f2, width=5)
e7.place(x=409, y=4 + offset_entry)
e7.insert(0, "4")
e7.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="Middle H").place(x=462 + offset_label_x, y=4 + offset_label_y)
e8 = Entry(f2, width=5)
e8.place(x=532, y=4 + offset_entry)
e8.insert(0, "2")
e8.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="Middle V").place(x=585 + offset_label_x, y=4 + offset_label_y)
e9 = Entry(f2, width=5)
e9.place(x=655, y=4 + offset_entry)
e9.insert(0, "2")
e9.bind("<Return>", calculation)

f3 = Frame(main_win, width=310, height=43, bd=2, relief=GROOVE)
f3.configure(background=bg_color)
f3.place(x=460, y=398)

rbvar1 = IntVar()
rb3 = Radiobutton(f3, text="p10", variable=rbvar1, value=3, bg=bg_color)
rb3.place(x=4, y=7)
rb3.select()

rb4 = Radiobutton(f3, text="p11", variable=rbvar1, value=4, bg=bg_color)
rb4.place(x=170, y=7)

f4 = Frame(main_win, width=200, height=97, bd=2, relief=GROOVE)
f4.configure(background=bg_color)
f4.place(x=780, y=398)

rbvar = IntVar()
rb1 = Radiobutton(f4,text="Mesures en centimètres",variable=rbvar,value=1,bg=bg_color,command=update_scale)
rb1.place(x=4, y=7)
rb1.select()

rb2 = Radiobutton(f4,text="Mesures en mètres",variable=rbvar,value=2,bg=bg_color,command=update_scale)
rb2.place(x=4, y=60)

main_win.mainloop()
0
Diablo76 Messages postés 161 Date d'inscription vendredi 25 novembre 2022 Statut Membre Dernière intervention 1 mai 2024 41
2 juin 2023 à 18:03

Salut Phil,

Voila,

Alors je viens de voir que la police utilisée sur mon Mac est différente que sur Windows.

Mac :

{'family': '.SF NS Text', 'size': 13, 'weight': 'normal', 'slant': 'roman', 'underline': 0, 'overstrike': 0}

Windows :

{'family': 'Segoe UI', 'size': 9, 'weight': 'normal', 'slant': 'roman', 'underline': 0, 'overstrike': 0}

Donc je pense qu'en modifiant la police et en jouant un peu sur le décalage ça devrait être bon, alors dis-moi si tu souhaite que je m'en occupe.

Regarde quand même quelle police est utilisée chez toi.

0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024 178
3 juin 2023 à 11:22

Bonjour Diablo,

Oui, si tu pouvais t'en occuper, de toutes façons je n'ai pas de Mac sous la main

pour faire une suite de tests  :-)

0
Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024 178
3 juin 2023 à 16:50

j'ai la même fonte que toi sur Windows ...

1
Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024 178
Modifié le 5 juin 2023 à 14:12

Bonjour Diablo,

Pour le moment, je préfère me concentrer sur mon code du 2 juin, avec les bons textes de labels

Tu me proposais de t'en occuper

Peux tu faire ça et m'envoyer le code stp ?

Il faut jouer sur les décalages, bien sur, mais comme je ne peux pas tester sur Mac ...

0
Diablo76 Messages postés 161 Date d'inscription vendredi 25 novembre 2022 Statut Membre Dernière intervention 1 mai 2024 41
5 juin 2023 à 14:57

Pas de soucis, voilà :

Si ça te convient.

Code :

# -*- coding:Utf-8 -*-

import sys
from math import *
from tkinter import *
from tkinter import messagebox

def get_os():
    if sys.platform in ("win32","linux"):
        font_default = ("Segoe UI", 9)
        return font_default,0,0,0,0
    else:
        font_default = ("Segoe UI", 10)
        return font_default,25,-0,15,-2

def calculation(evt):
    graph_area.create_rectangle(100, 100, 300, 300, fill="orange")

def update_scale():
    e6.delete(0, END)
    e7.delete(0, END)
    e8.delete(0, END)
    e9.delete(0, END)

    if rbvar.get() == 1:
        e6.insert(0, "4")
        e7.insert(0, "4")
        e8.insert(0, "2")
        e9.insert(0, "2")
    else:
        e6.insert(0, "0.04")
        e7.insert(0, "0.04")
        e8.insert(0, "0.02")
        e9.insert(0, "0.02")

bg_color = "lightsteelblue"
WIDTH, HEIGHT = 1000, 505
font_default, offset_label_x, offset_label_y, offset_entry_x, offset_entry_y = get_os()


main_win = Tk()
main_win.geometry(str(WIDTH) + "x" + str(HEIGHT) + "+200+50")
main_win.title("Test")
main_win.configure(background=bg_color)

graph_area = Canvas(main_win, width=WIDTH - 20, height=HEIGHT - 155, bg="ivory")
graph_area.place(x=10, y=10)

f1 = LabelFrame(main_win, width=440, height=50, bd=2, relief=GROOVE, text="F1 ", font=font_default)
f1.configure(background=bg_color)
f1.place(x=10, y=390)

Label(f1, bg=bg_color, text="Hauteur", font=font_default).place(x=5, y=4 + offset_label_y)
e1 = Entry(f1, width=5, font=font_default)
e1.place(x=65, y=4 + offset_entry_y)
e1.bind("<Return>", calculation)
e1.focus()

Label(f1, bg=bg_color, text="Longueur pente", font=font_default).place(x=110 + offset_label_x, y=4 + offset_label_y)
e2 = Entry(f1, width=5, font=font_default)
e2.place(x=210+offset_entry_x, y=4 + offset_entry_y)
e2.bind("<Return>", calculation)

Label(f1, bg=bg_color, text="Longueur sommet", font=font_default).place(x=254 + offset_label_x, y=4 + offset_label_y)
e3 = Entry(f1, width=5, font=font_default)
e3.place(x=366+offset_entry_x, y=4 + offset_entry_y)
e3.insert(0, "0.0")
e3.bind("<Return>", calculation)

f2 = LabelFrame(main_win, width=760, height=50, bd=2, relief=GROOVE, text="F2 ", font=font_default)
f2.configure(background=bg_color)
f2.place(x=10, y=445)

Label(f2, bg=bg_color, text="Longueur", font=font_default).place(x=5, y=4 + offset_label_y)
e4 = Entry(f2, width=5, font=font_default)
e4.place(x=65, y=4 + offset_entry_y)
e4.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="Largeur", font=font_default).place(x=110 + offset_label_x, y=4 + offset_label_y)
e5 = Entry(f2, width=5, font=font_default)
e5.place(x=163+offset_entry_x, y=4 + offset_entry_y)
e5.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="External H", font=font_default).place(x=216 + offset_label_x, y=4 + offset_label_y)
e6 = Entry(f2, width=5, font=font_default)
e6.place(x=286+offset_entry_x, y=4 + offset_entry_y)
e6.insert(0, "4")
e6.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="External V", font=font_default).place(x=339 + offset_label_x, y=4 + offset_label_y)
e7 = Entry(f2, width=5, font=font_default)
e7.place(x=409+offset_entry_x, y=4 + offset_entry_y)
e7.insert(0, "4")
e7.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="Middle H", font=font_default).place(x=462 + offset_label_x, y=4 + offset_label_y)
e8 = Entry(f2, width=5, font=font_default)
e8.place(x=532+offset_entry_x, y=4 + offset_entry_y)
e8.insert(0, "2")
e8.bind("<Return>", calculation)

Label(f2, bg=bg_color, text="Middle V", font=font_default).place(x=585 + offset_label_x, y=4 + offset_label_y)
e9 = Entry(f2, width=5, font=font_default)
e9.place(x=655+offset_entry_x, y=4 + offset_entry_y)
e9.insert(0, "2")
e9.bind("<Return>", calculation)

f3 = Frame(main_win, width=310, height=43, bd=2, relief=GROOVE)
f3.configure(background=bg_color)
f3.place(x=460, y=398)

rbvar1 = IntVar()
rb3 = Radiobutton(f3, text="p10", variable=rbvar1, value=3, bg=bg_color, font=font_default)
rb3.place(x=4, y=7)
rb3.select()

rb4 = Radiobutton(f3, text="p11", variable=rbvar1, value=4, bg=bg_color, font=font_default)
rb4.place(x=170, y=7)

f4 = Frame(main_win, width=200, height=97, bd=2, relief=GROOVE)
f4.configure(background=bg_color)
f4.place(x=780, y=398)

rbvar = IntVar()
rb1 = Radiobutton(f4,text="Mesures en centimètres",variable=rbvar,value=1,bg=bg_color,command=update_scale, font=font_default)
rb1.place(x=4, y=7)
rb1.select()

rb2 = Radiobutton(f4,text="Mesures en mètres",variable=rbvar,value=2,bg=bg_color,command=update_scale, font=font_default)
rb2.place(x=4, y=60)

main_win.mainloop()
0
Diablo76 Messages postés 161 Date d'inscription vendredi 25 novembre 2022 Statut Membre Dernière intervention 1 mai 2024 41
5 juin 2023 à 15:48

Bon.. les filles, ce ne serait pas mieux de monter un Git plutôt que de polluer le forum ? 

0
Phil_1857 Messages postés 1883 Date d'inscription lundi 23 mars 2020 Statut Membre Dernière intervention 28 février 2024 178
5 juin 2023 à 16:01

;-)  :-)  :-)

Merci, ca devrait aller maintenant

0

Salut Diablo76.

Comme cela m'intrigue, je me demande si sur MacOs, ce n'est pas une autre unité qui est utilisée (pouces, points, mm, cm), au lieu du pixel.

Peux-tu tester ce code qui spécifie les unités avec les pads et autres options et dire ce que ça donne.

import tkinter as tk
from tkinter import font as tk_font

BG_COLOR = 'lightsteelblue'
GRAPH_AREA_WIDTH = 980
GRAPH_AREA_HEIGHT = 20
GRAPH_AREA_BG = 'ivory'


class RadioButton(tk.Radiobutton):
    def __init__(self, master, text, font, var, value, command=None):
        options = dict(
            activebackground='navy',  # survol souris
            activeforeground=BG_COLOR,  # survol souris
            background=BG_COLOR,
            foreground='navy',
            disabledforeground='grey',  # lorsque state=tk.DISABLED
            highlightbackground=BG_COLOR,  # sans focus (via touche tab)
            highlightcolor='navy',  # en focus (via touche tab)
            selectcolor='white',
            borderwidth=0,
            text=text,
            variable=var,
            value=value,
            command=command,
        )
        super().__init__(master, options)


class Entry(tk.Entry):
    def __init__(self, master, value, font):
        options = dict(
            background='lightBlue',
            disabledbackground='#000',
            disabledforeground='#999',
            font=font,
            foreground='#333',
            highlightbackground=BG_COLOR,
            highlightcolor='navy',
            highlightthickness='1px',
            insertbackground='#333',
            readonlybackground='#666',
            selectbackground='#fff',
            selectforeground='#000',
            text=value,
            width=5,
        )
        super().__init__(master, options)


class Label(tk.Label):
    def __init__(self, master, text, font):
        options = dict(
            background=BG_COLOR, font=font, foreground='navy', padx='5px', pady=0, text=text
        )
        super().__init__(master, options)


class LabelFrame(tk.LabelFrame):
    def __init__(self, master, title='', font=None):
        options = dict(
            background=BG_COLOR,
            border='2px',
            foreground='#fff',
            labelanchor=tk.NW,
            padx='5px',
            pady=0,
            relief=tk.GROOVE,
        )
        if title:
            assert isinstance(font, tk_font.Font)
            self.label = tk.Label(
                master, text=title, font=font, bg=BG_COLOR, fg='darkBlue', bd=0, pady=0, padx='3px'
            )
            options['labelwidget'] = self.label
        super().__init__(master, options)


class ItemFrame(tk.Frame):
    def __init__(self, master, text, font, default_value=''):
        super().__init__(master)
        self.label = Label(self, text, font)
        self.label.grid(sticky=tk.NS)
        self.entry = Entry(self, value=default_value, font=font)
        self.entry.grid(row=0, column=1)


def calculation(evt):
    pass


def update_scale():
    pass


main_win = tk.Tk()
main_win.title('Test')
main_win.config(bg=BG_COLOR, padx=10, pady=10)

title_font = tk_font.Font(main_win, family='serif', size=-15)
text_font = tk_font.Font(main_win, family='serif', size=-13)

main_win.columnconfigure(0, weight=1)
main_win.columnconfigure(1, weight=1)
main_win.columnconfigure(2, weight=0)

graph_area = tk.Canvas(
    main_win, width=GRAPH_AREA_WIDTH, height=GRAPH_AREA_HEIGHT, bg=GRAPH_AREA_BG
)
graph_area.grid(row=0, column=0, columnspan=3, pady=(0, 15))

entries = {}

area_1 = LabelFrame(main_win, 'F1', title_font)
area_1.grid(row=1, column=0, padx='5px', ipady='5px', sticky=tk.NSEW)
pady_top = f'{title_font.metrics("linespace") // 2 - 2}px'
# print('via metric : ', pady_top, end=', ')
# pady_top = f'{area_1.label.winfo_reqheight() // 2 - 2}px'
# print('via reqheight : ', pady_top)

area_2 = LabelFrame(main_win)
area_2.grid(row=1, column=1, padx='5px', pady=(pady_top, 0), ipady='5px', sticky=tk.NSEW)
area_2.rowconfigure(0, weight=1)

area_3 = LabelFrame(main_win)
area_3.grid(
    row=1, column=2, rowspan=2, padx='5px', pady=(pady_top, 0), ipady='5px', sticky=tk.NSEW
)

area_4 = LabelFrame(main_win, 'F2', title_font)
area_4.grid(row=2, column=0, columnspan=2, padx='5px', pady=('10px', 0), ipady='5px', sticky=tk.EW)

for col, text in enumerate(('p1', 'p2', 'p3')):
    area_1.columnconfigure(col, weight=1)
    item_frame = ItemFrame(area_1, text, text_font)
    item_frame.grid(row=0, column=col)
    item_frame.entry.bind('<Return>', calculation)
    entries[text] = item_frame.entry

int_var_pn = tk.IntVar(name='pn')
for col, (text, value) in enumerate((('p10', 3), ('p11', 4))):
    area_2.columnconfigure(col, weight=1)
    rbutton = RadioButton(area_2, text, text_font, int_var_pn, value)
    rbutton.grid(row=0, column=col)
    if col == 0:
        rbutton.select()

int_var_mes = tk.IntVar(name='mesure')
for row, (text, value) in enumerate((('centimètres', 1), ('mètres', 2))):
    rbutton = RadioButton(
        area_3, f"Mesures en {text}", text_font, int_var_mes, value, update_scale
    )
    rbutton.grid(row=row, column=0, sticky=tk.W, padx='10px', pady='10px')
    if row == 0:
        rbutton.select()

for col, (text, value) in enumerate(((4, ''), (5, ''), (6, '4'), (7, '4'), (8, '2'), (9, '2'))):
    area_4.columnconfigure(col, weight=1)
    item_frame = ItemFrame(area_4, f'p{text}', text_font)
    item_frame.grid(row=0, column=col)
    item_frame.entry.bind('<Return>', calculation)
    entries[text] = item_frame.entry

main_win.mainloop()

Sur mon système, j'obtiens :

https://www.cjoint.com/data/MFgjrpHjiVU_modif.png

Je pense que sur Windows, cela doit être identique.

Si ça diffère encore sur Macos, je ne vois plus trop ce qui pourrait provoquer cela, tkinter/Tcl sur python est toujours en 8.6, puis je ne pense pas qu'en 8.7 cela change grand chose à ce niveau.

0
Diablo76 Messages postés 161 Date d'inscription vendredi 25 novembre 2022 Statut Membre Dernière intervention 1 mai 2024 41
6 juin 2023 à 11:58

Salut plochu,

Non là ça me parait bien hormis la fonte qui est différente.

0
plochu > Diablo76 Messages postés 161 Date d'inscription vendredi 25 novembre 2022 Statut Membre Dernière intervention 1 mai 2024
6 juin 2023 à 12:32

Merci  8=)

Pour la police, c'est normal, puisqu'en spécifiant 'serif', c'est la police serif par défaut du système qui sera utilisée, en revanche toujours ce petit décalage des 2 pixels avec les labelframes sans titres :-/, si je ne les soustrait pas chez moi, j'ai un décalage vers le bas, c'est via le label dans LabelFrame et la variable pady_top que cela se joue, enfin 2px de différence ça va, c'est acceptable ^^

Si tu enlèves les unités du code (un simple rechercher/remplacer de px par rien), est-ce que le résultat est identique ? De façon à confirmer que c'est bien une histoire d'unités.

0
Diablo76 Messages postés 161 Date d'inscription vendredi 25 novembre 2022 Statut Membre Dernière intervention 1 mai 2024 41
7 juin 2023 à 15:09

Salut plochu,

j'ai supprimé les px et l'apparence est identique à l'image ci-dessus.

0

Salut Diablo76.

D'accord, merci de l'info, rien à voir donc avec les unités.

0