鱼C论坛

 找回密码
 立即注册
查看: 3387|回复: 6

关于easygui选择框大小问题

[复制链接]
发表于 2018-1-18 17:02:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
系统是win7x64,python版本是3.63,用pip安装了easygui0.98,在尝试修改choice_box的宽高时,发现其与0.96还是有点区别的,只在choice_box.py文件里找到了以下代码
  1.     def config_root(self, title):

  2.         screen_width = self.boxRoot.winfo_screenwidth()
  3.         screen_height = self.boxRoot.winfo_screenheight()
  4.         self.root_width = int((screen_width * 0.8))
  5.         root_height = int((screen_height * 0.4))

  6.         self.boxRoot.title(title)
  7.         self.boxRoot.iconname('Dialog')
  8.         self.boxRoot.expand = tk.NO
  9.         # self.boxRoot.minsize(width=62 * self.calc_character_width())

  10.         self.set_pos()

  11.         self.boxRoot.protocol('WM_DELETE_WINDOW', self.x_pressed)
  12.         self.boxRoot.bind('<Any-Key>', self.KeyboardListener)
  13.         self.boxRoot.bind("<Escape>", self.cancel_pressed)
复制代码


修改上面的宽高,并没有产生实际变化
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-1-18 19:39:34 | 显示全部楼层
你这冒似要人家填空吧。你的代码未必是商业的。就不能好好的把代码上全。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-1-18 19:43:24 | 显示全部楼层
ba21 发表于 2018-1-18 19:39
你这冒似要人家填空吧。你的代码未必是商业的。就不能好好的把代码上全。

代码是easygui0.98里的choice_box.py文件,太长了我就没附上全部的


  1. import collections
  2. import string

  3. try:
  4.     from . import global_state
  5.     from .base_boxes import bindArrows
  6. except (SystemError, ValueError, ImportError):
  7.     import global_state
  8.     from base_boxes import bindArrows

  9. try:
  10.     import tkinter as tk  # python 3
  11.     import tkinter.font as tk_Font
  12. except:
  13.     import Tkinter as tk  # python 2
  14.     import tkFont as tk_Font


  15. def choicebox(msg="Pick an item", title="", choices=[], preselect=0,
  16.               callback=None,
  17.               run=True):
  18.     """
  19.     Present the user with a list of choices.
  20.     return the choice that he selects.

  21.     :param str msg: the msg to be displayed
  22.     :param str title: the window title
  23.     :param list choices: a list or tuple of the choices to be displayed
  24.     :param preselect: Which item, if any are preselected when dialog appears
  25.     :return: List containing choice selected or None if cancelled
  26.     """
  27.     mb = ChoiceBox(msg, title, choices, preselect=preselect,
  28.                    multiple_select=False,
  29.                    callback=callback)
  30.     if run:
  31.         reply = mb.run()
  32.         return reply
  33.     else:
  34.         return mb


  35. def multchoicebox(msg="Pick an item", title="", choices=[],
  36.                   preselect=0, callback=None,
  37.                   run=True):
  38.     """ Same as choicebox, but the user can select many items.

  39.     """
  40.     mb = ChoiceBox(msg, title, choices, preselect=preselect,
  41.                    multiple_select=True,
  42.                    callback=callback)
  43.     if run:
  44.         reply = mb.run()
  45.         return reply
  46.     else:
  47.         return mb


  48. # Utility function.  But, is it generic enough to be moved out of here?
  49. def make_list_or_none(obj, cast_type=None):
  50.     # -------------------------------------------------------------------
  51.     # for an object passed in, put it in standardized form.
  52.     # It may be None.  Just return None
  53.     # If it is a scalar, attempt to cast it into cast_type.  Raise error
  54.     # if not possible.  Convert scalar to a single-element list.
  55.     # If it is a collections.Sequence (including a scalar converted to let),
  56.     # then cast each element to cast_type.  Raise error if any cannot be converted.
  57.     # -------------------------------------------------------------------
  58.     ret_val = obj
  59.     if ret_val is None:
  60.         return None
  61.     # Convert any non-sequence to single-element list
  62.     if not isinstance(obj, collections.Sequence):
  63.         if cast_type is not None:
  64.             try:
  65.                 ret_val = cast_type(obj)
  66.             except Exception as e:
  67.                 raise Exception("Value {} cannot be converted to type: {}".format(obj, cast_type))
  68.         ret_val = [ret_val,]
  69.     # Convert all elements to cast_type
  70.     if cast_type is not None:
  71.         try:
  72.             ret_val = [cast_type(elem) for elem in ret_val]
  73.         except:
  74.             raise Exception("Not all values in {}\n can be converted to type: {}".format(ret_val, cast_type))
  75.     return ret_val
  76.                         
  77.                         
  78. class ChoiceBox(object):

  79.     def __init__(self, msg, title, choices, preselect, multiple_select, callback):

  80.         self.callback = callback

  81.         self.choices = self.to_list_of_str(choices)

  82.         # Convert preselect to always be a list or None.
  83.         preselect_list = make_list_or_none(preselect, cast_type=int)
  84.         if not multiple_select and len(preselect_list)>1:
  85.             raise ValueError("Multiple selections not allowed, yet preselect has multiple values:{}".format(preselect_list))
  86.         
  87.         self.ui = GUItk(msg, title, self.choices, preselect_list, multiple_select,
  88.                         self.callback_ui)

  89.     def run(self):
  90.         """ Start the ui """
  91.         self.ui.run()
  92.         self.ui = None
  93.         return self.choices

  94.     def stop(self):
  95.         """ Stop the ui """
  96.         self.ui.stop()

  97.     def callback_ui(self, ui, command, choices):
  98.         """ This method is executed when ok, cancel, or x is pressed in the ui.
  99.         """
  100.         if command == 'update':  # OK was pressed
  101.             self.choices = choices
  102.             if self.callback:
  103.                 # If a callback was set, call main process
  104.                 self.callback(self)
  105.             else:
  106.                 self.stop()
  107.         elif command == 'x':
  108.             self.stop()
  109.             self.choices = None
  110.         elif command == 'cancel':
  111.             self.stop()
  112.             self.choices = None

  113.     # methods to change properties --------------

  114.     @property
  115.     def msg(self):
  116.         """Text in msg Area"""
  117.         return self._msg

  118.     @msg.setter
  119.     def msg(self, msg):
  120.         self.ui.set_msg(msg)

  121.     @msg.deleter
  122.     def msg(self):
  123.         self._msg = ""
  124.         self.ui.set_msg(self._msg)

  125.     # Methods to validate what will be sent to ui ---------

  126.     def to_list_of_str(self, choices):
  127.         # -------------------------------------------------------------------
  128.         # If choices is a tuple, we make it a list so we can sort it.
  129.         # If choices is already a list, we make a new list, so that when
  130.         # we sort the choices, we don't affect the list object that we
  131.         # were given.
  132.         # -------------------------------------------------------------------
  133.         choices = list(choices)

  134.         choices = [str(c) for c in choices]

  135.         while len(choices) < 2:
  136.             choices.append("Add more choices")

  137.         return choices

  138.                

  139. class GUItk(object):

  140.     """ This object contains the tk root object.
  141.         It draws the window, waits for events and communicates them
  142.         to MultiBox, together with the entered values.

  143.         The position in wich it is drawn comes from a global variable.

  144.         It also accepts commands from Multibox to change its message.
  145.     """

  146.     def __init__(self, msg, title, choices, preselect, multiple_select, callback):

  147.         self.callback = callback

  148.         self.choices = choices

  149.         self.width_in_chars = global_state.prop_font_line_length
  150.         # Initialize self.selected_choices
  151.         # This is the value that will be returned if the user clicks the close
  152.         # icon
  153.         # self.selected_choices = None

  154.         self.multiple_select = multiple_select

  155.         self.boxRoot = tk.Tk()

  156.         self.boxFont = tk_Font.nametofont("TkTextFont")

  157.         self.config_root(title)

  158.         self.set_pos(global_state.window_position)  # GLOBAL POSITION

  159.         self.create_msg_widget(msg)

  160.         self.create_choicearea()

  161.         self.create_ok_button()

  162.         self.create_cancel_button()

  163.         self. create_special_buttons()
  164.         
  165.         self.preselect_choice(preselect)

  166.         self.choiceboxWidget.focus_force()

  167.     # Run and stop methods ---------------------------------------

  168.     def run(self):
  169.         self.boxRoot.mainloop()  # run it!
  170.         self.boxRoot.destroy()   # Close the window

  171.     def stop(self):
  172.         # Get the current position before quitting
  173.         self.get_pos()

  174.         self.boxRoot.quit()

  175.     def x_pressed(self):
  176.         self.callback(self, command='x', choices=self.get_choices())

  177.     def cancel_pressed(self, event):
  178.         self.callback(self, command='cancel', choices=self.get_choices())

  179.     def ok_pressed(self, event):
  180.         self.callback(self, command='update', choices=self.get_choices())

  181.     # Methods to change content ---------------------------------------

  182.     # Methods to change content ---------------------------------------

  183.     def set_msg(self, msg):
  184.         self.messageArea.config(state=tk.NORMAL)
  185.         self.messageArea.delete(1.0, tk.END)
  186.         self.messageArea.insert(tk.END, msg)
  187.         self.messageArea.config(state=tk.DISABLED)
  188.         # Adjust msg height
  189.         self.messageArea.update()
  190.         numlines = self.get_num_lines(self.messageArea)
  191.         self.set_msg_height(numlines)
  192.         self.messageArea.update()
  193.         # put the focus on the entryWidget

  194.     def set_msg_height(self, numlines):
  195.         self.messageArea.configure(height=numlines)

  196.     def get_num_lines(self, widget):
  197.         end_position = widget.index(tk.END)  # '4.0'
  198.         end_line = end_position.split('.')[0]  # 4
  199.         return int(end_line) + 1  # 5

  200.     def set_pos(self, pos=None):
  201.         if not pos:
  202.             pos = global_state.window_position
  203.         self.boxRoot.geometry(pos)

  204.     def get_pos(self):
  205.         # The geometry() method sets a size for the window and positions it on
  206.         # the screen. The first two parameters are width and height of
  207.         # the window. The last two parameters are x and y screen coordinates.
  208.         # geometry("250x150+300+300")
  209.         geom = self.boxRoot.geometry()  # "628x672+300+200"
  210.         global_state.window_position = '+' + geom.split('+', 1)[1]

  211.     def preselect_choice(self, preselect):
  212.         #print(preselect)
  213.         if preselect != None:
  214.             for v in preselect:
  215.                 self.choiceboxWidget.select_set(v)
  216.                 self.choiceboxWidget.activate(v)

  217.     def get_choices(self):
  218.         choices_index = self.choiceboxWidget.curselection()
  219.         if not choices_index:
  220.             return None
  221.         if self.multiple_select:
  222.             selected_choices = [self.choiceboxWidget.get(index)
  223.                                 for index in choices_index]
  224.         else:
  225.             selected_choices = self.choiceboxWidget.get(choices_index)

  226.         return selected_choices

  227.     # Auxiliary methods -----------------------------------------------
  228.     def calc_character_width(self):
  229.         char_width = self.boxFont.measure('W')
  230.         return char_width

  231.     def config_root(self, title):

  232.         screen_width = self.boxRoot.winfo_screenwidth()
  233.         screen_height = self.boxRoot.winfo_screenheight()
  234.         self.root_width = int((screen_width * 0.3))
  235.         root_height = int((screen_height * 0.2))

  236.         self.boxRoot.title(title)
  237.         self.boxRoot.iconname('Dialog')
  238.         self.boxRoot.expand = tk.NO
  239.         # self.boxRoot.minsize(width=62 * self.calc_character_width())

  240.         self.set_pos()

  241.         self.boxRoot.protocol('WM_DELETE_WINDOW', self.x_pressed)
  242.         self.boxRoot.bind('<Any-Key>', self.KeyboardListener)
  243.         self.boxRoot.bind("<Escape>", self.cancel_pressed)

  244.     def create_msg_widget(self, msg):

  245.         if msg is None:
  246.             msg = ""

  247.         self.msgFrame = tk.Frame(
  248.             self.boxRoot,
  249.             padx=2 * self.calc_character_width(),

  250.         )
  251.         self.messageArea = tk.Text(
  252.             self.msgFrame,
  253.             width=self.width_in_chars,
  254.             state=tk.DISABLED,
  255.             background=self.boxRoot.config()["background"][-1],
  256.             relief='flat',
  257.             padx=(global_state.default_hpad_in_chars *
  258.                   self.calc_character_width()),
  259.             pady=(global_state.default_hpad_in_chars *
  260.                   self.calc_character_width()),
  261.             wrap=tk.WORD,

  262.         )
  263.         self.set_msg(msg)

  264.         self.msgFrame.pack(side=tk.TOP, expand=1, fill='both')

  265.         self.messageArea.pack(side=tk.TOP, expand=1, fill='both')

  266.     def create_choicearea(self):

  267.         self.choiceboxFrame = tk.Frame(master=self.boxRoot)
  268.         self.choiceboxFrame.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)

  269.         lines_to_show = min(len(self.choices), 20)

  270.         # --------  put the self.choiceboxWidget in the self.choiceboxFrame ---
  271.         self.choiceboxWidget = tk.Listbox(self.choiceboxFrame,
  272.                                           height=lines_to_show,
  273.                                           borderwidth="1m", relief="flat",
  274.                                           bg="white"
  275.                                           )

  276.         if self.multiple_select:
  277.             self.choiceboxWidget.configure(selectmode=tk.MULTIPLE)

  278.         # self.choiceboxWidget.configure(font=(global_state.PROPORTIONAL_FONT_FAMILY,
  279.         #                                      global_state.PROPORTIONAL_FONT_SIZE))

  280.         # add a vertical scrollbar to the frame
  281.         rightScrollbar = tk.Scrollbar(self.choiceboxFrame, orient=tk.VERTICAL,
  282.                                       command=self.choiceboxWidget.yview)
  283.         self.choiceboxWidget.configure(yscrollcommand=rightScrollbar.set)

  284.         # add a horizontal scrollbar to the frame
  285.         bottomScrollbar = tk.Scrollbar(self.choiceboxFrame,
  286.                                        orient=tk.HORIZONTAL,
  287.                                        command=self.choiceboxWidget.xview)
  288.         self.choiceboxWidget.configure(xscrollcommand=bottomScrollbar.set)

  289.         # pack the Listbox and the scrollbars.
  290.         # Note that although we must define
  291.         # the textArea first, we must pack it last,
  292.         # so that the bottomScrollbar will
  293.         # be located properly.

  294.         bottomScrollbar.pack(side=tk.BOTTOM, fill=tk.X)
  295.         rightScrollbar.pack(side=tk.RIGHT, fill=tk.Y)

  296.         self.choiceboxWidget.pack(
  297.             side=tk.LEFT, padx="1m", pady="1m", expand=tk.YES, fill=tk.BOTH)

  298.         # Insert choices widgets
  299.         for choice in self.choices:
  300.             self.choiceboxWidget.insert(tk.END, choice)

  301.         # Bind the keyboard events
  302.         self.choiceboxWidget.bind("<Return>", self.ok_pressed)
  303.         self.choiceboxWidget.bind("<Double-Button-1>",
  304.                                   self.ok_pressed)

  305.     def create_ok_button(self):

  306.         self.buttonsFrame = tk.Frame(self.boxRoot)
  307.         self.buttonsFrame.pack(side=tk.TOP, expand=tk.YES, pady=0)

  308.         # put the buttons in the self.buttonsFrame
  309.         okButton = tk.Button(self.buttonsFrame, takefocus=tk.YES,
  310.                              text="OK", height=1, width=6)
  311.         bindArrows(okButton)
  312.         okButton.pack(expand=tk.NO, side=tk.RIGHT, padx='2m', pady='1m',
  313.                       ipady="1m", ipadx="2m")

  314.         # for the commandButton, bind activation events
  315.         okButton.bind("<Return>", self.ok_pressed)
  316.         okButton.bind("<Button-1>", self.ok_pressed)
  317.         okButton.bind("<space>", self.ok_pressed)

  318.     def create_cancel_button(self):
  319.         cancelButton = tk.Button(self.buttonsFrame, takefocus=tk.YES,
  320.                                  text="Cancel", height=1, width=6)
  321.         bindArrows(cancelButton)
  322.         cancelButton.pack(expand=tk.NO, side=tk.LEFT, padx='2m', pady='1m',
  323.                           ipady="1m", ipadx="2m")
  324.         cancelButton.bind("<Return>", self.cancel_pressed)
  325.         cancelButton.bind("<Button-1>", self.cancel_pressed)
  326.         # self.cancelButton.bind("<Escape>", self.cancel_pressed)
  327.         # for the commandButton, bind activation events to the activation event
  328.         # handler

  329.     def create_special_buttons(self):
  330.         # add special buttons for multiple select features
  331.         if not self.multiple_select:
  332.             return

  333.         selectAllButton = tk.Button(
  334.             self.buttonsFrame, text="Select All", height=1, width=6)
  335.         selectAllButton.pack(expand=tk.NO, side=tk.LEFT, padx='2m',
  336.                              pady='1m',
  337.                              ipady="1m", ipadx="2m")

  338.         clearAllButton = tk.Button(self.buttonsFrame, text="Clear All",
  339.                                    height=1, width=6)
  340.         clearAllButton.pack(expand=tk.NO, side=tk.LEFT,
  341.                             padx='2m', pady='1m',
  342.                             ipady="1m", ipadx="2m")

  343.         selectAllButton.bind("<Button-1>", self.choiceboxSelectAll)
  344.         bindArrows(selectAllButton)
  345.         clearAllButton.bind("<Button-1>", self.choiceboxClearAll)
  346.         bindArrows(clearAllButton)

  347.     def KeyboardListener(self, event):
  348.         key = event.keysym
  349.         if len(key) <= 1:
  350.             if key in string.printable:
  351.                 # Find the key in the liglobal_state.
  352.                 # before we clear the list, remember the selected member
  353.                 try:
  354.                     start_n = int(self.choiceboxWidget.curselection()[0])
  355.                 except IndexError:
  356.                     start_n = -1

  357.                 # clear the selection.
  358.                 self.choiceboxWidget.selection_clear(0, 'end')

  359.                 # start from previous selection +1
  360.                 for n in range(start_n + 1, len(self.choices)):
  361.                     item = self.choices[n]
  362.                     if item[0].lower() == key.lower():
  363.                         self.choiceboxWidget.selection_set(first=n)
  364.                         self.choiceboxWidget.see(n)
  365.                         return
  366.                 else:
  367.                     # has not found it so loop from top
  368.                     for n, item in enumerate(self.choices):
  369.                         if item[0].lower() == key.lower():
  370.                             self.choiceboxWidget.selection_set(first=n)
  371.                             self.choiceboxWidget.see(n)
  372.                             return

  373.                     # nothing matched -- we'll look for the next logical choice
  374.                     for n, item in enumerate(self.choices):
  375.                         if item[0].lower() > key.lower():
  376.                             if n > 0:
  377.                                 self.choiceboxWidget.selection_set(
  378.                                     first=(n - 1))
  379.                             else:
  380.                                 self.choiceboxWidget.selection_set(first=0)
  381.                             self.choiceboxWidget.see(n)
  382.                             return

  383.                     # still no match (nothing was greater than the key)
  384.                     # we set the selection to the first item in the list
  385.                     lastIndex = len(self.choices) - 1
  386.                     self.choiceboxWidget.selection_set(first=lastIndex)
  387.                     self.choiceboxWidget.see(lastIndex)
  388.                     return

  389.     def choiceboxClearAll(self, event):
  390.         self.choiceboxWidget.selection_clear(0, len(self.choices) - 1)

  391.     def choiceboxSelectAll(self, event):
  392.         self.choiceboxWidget.selection_set(0, len(self.choices) - 1)

  393. if __name__ == '__main__':
  394.     users_choice = multchoicebox(choices=['choice1', 'choice2'])
  395.     print("User's choice is: {}".format(users_choice))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-18 20:00:44 | 显示全部楼层
        self.root_width = int((screen_width * 0.3))
        root_height = int((screen_height * 0.2))

这里少了个self吧
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-1-18 20:21:31 | 显示全部楼层
ba21 发表于 2018-1-18 20:00
self.root_width = int((screen_width * 0.3))
        root_height = int((screen_height * 0.2) ...

没有变化,这里安装好本来就是没有self的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-18 22:00:58 | 显示全部楼层
orino 发表于 2018-1-18 20:21
没有变化,这里安装好本来就是没有self的

好吧。安装的easygui特殊些。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 11:02:53 | 显示全部楼层
朋友,最后咋解决的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-16 09:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表